/**
 * UI Components for AIChat吉PT userscript.
 * Handles creation and management of UI elements.
 */
import { scrollToTop, hasFocus } from "../utils/domUtils";
import "../styles/main.css";

// Add this code at the top of the file to include highlight.js
// Look for the style tag additions at the beginning and add after them:

// 添加highlight.js的CSS
const highlightCss = document.createElement("link");
highlightCss.rel = "stylesheet";
highlightCss.href =
  "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css";
document.head.appendChild(highlightCss);

// 添加highlight.js脚本
const highlightScript = document.createElement("script");
highlightScript.src =
  "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js";
document.head.appendChild(highlightScript);

// 添加marked.js用于Markdown解析
const markedScript = document.createElement("script");
markedScript.src = "https://cdn.jsdelivr.net/npm/marked/marked.min.js";
document.head.appendChild(markedScript);

/**
 * Creates and sets up all UI components for the userscript
 * @param {Function} chatRunner - Function to handle chat interactions
 * @param {Function} messageReceiver - Function to handle message events
 * @returns {Object} UI elements and state
 */
export function setupUIComponents(chatRunner, chatCustomizeRunner) {
  const ui = {
    elements: {},
    state: {
      aiDivMainVisible: false,
    },
  };

  // Create main AI panel
  ui.elements.aiDivMain = createAiPanel();
  ui.elements.aiTool = createAiTool();
  ui.elements.selectBox = createModelSelector();
  ui.elements.aiDiv2 = createAiOutputContainer();
  ui.elements.buttondiv = createInputContainer();
  ui.elements.chatInput = createChatInput(chatCustomizeRunner);
  ui.elements.button = createButton();

  // Append all elements to the correct parents
  appendUIElements(ui.elements);

  // Set up event listeners
  setupEventListeners(ui.elements, chatCustomizeRunner);

  // 创建初始提示
  createInitialTooltip();

  // 初始化欢迎界面
  setTimeout(() => {
    initializeWelcomeGreeting();
  }, 500);

  // 添加代码包按钮到左侧菜单
  setTimeout(() => {
    addCodePackageButton();
  }, 1000);

  return ui;
}

/**
 * 创建初始提示，告诉用户鼠标移动到右侧可以展示对话框
 */
function createInitialTooltip() {
  // 添加样式
  const tooltipStyle = document.createElement("style");
  tooltipStyle.textContent = `
    .aiChat-tooltip-container {
      position: fixed;
      right: 20px;
      bottom: 80px;
      z-index: 9999;
      animation: fadeIn 0.8s ease;
      filter: drop-shadow(0 5px 15px rgba(0, 0, 0, 0.15));
    }
    
    .aiChat-tooltip {
      position: relative;
      background: linear-gradient(135deg, rgba(77, 138, 240, 0.95), rgba(99, 230, 190, 0.95));
      color: white;
      padding: 18px 20px;
      border-radius: 14px;
      font-size: 15px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      max-width: 280px;
      text-align: center;
      cursor: pointer;
      backdrop-filter: blur(8px);
      border: 1px solid rgba(255, 255, 255, 0.3);
      font-weight: 500;
      line-height: 1.5;
      animation: float 3s ease-in-out infinite;
      overflow: hidden;
    }
    
    /* 添加装饰背景元素 */
    .aiChat-tooltip:before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
      transform: rotate(-45deg);
      pointer-events: none;
      z-index: -1;
    }
    
    .aiChat-tooltip-title {
      font-weight: bold;
      margin-bottom: 8px;
      font-size: 16px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 20px;
      padding: 4px 12px;
      display: inline-block;
      position: relative;
      overflow: hidden;
    }
    
    /* 标题光效 */
    .aiChat-tooltip-title:after {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, 
        rgba(255,255,255,0) 0%, 
        rgba(255,255,255,0.3) 50%, 
        rgba(255,255,255,0) 100%
      );
      animation: shimmer 3s infinite;
      pointer-events: none;
    }
    
    @keyframes shimmer {
      0% { left: -100%; }
      100% { left: 100%; }
    }
    
    .aiChat-tooltip:after {
      content: '';
      position: absolute;
      right: 20px;
      bottom: -10px;
      width: 0;
      height: 0;
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
      border-top: 10px solid rgba(99, 230, 190, 0.95);
    }
    
    .aiChat-tooltip-text {
      position: relative;
      z-index: 2;
    }
    
    .aiChat-tooltip-arrow {
      position: fixed;
      right: 10px;
      bottom: 35px;
      width: 40px;
      height: 40px;
      border-right: 3px solid rgba(99, 230, 190, 0.9);
      border-bottom: 3px solid rgba(99, 230, 190, 0.9);
      transform: rotate(-45deg);
      animation: pulse 2s infinite, moveRight 1.5s ease-in-out infinite;
      z-index: 9998;
      filter: drop-shadow(0 0 5px rgba(99, 230, 190, 0.6));
    }
    
    /* 添加装饰图标 */
    .aiChat-tooltip-icon {
      position: absolute;
      width: 24px;
      height: 24px;
      opacity: 0.2;
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
      z-index: 1;
    }
    
    .aiChat-icon-1 {
      top: 10px;
      left: 10px;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolygon points='12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2'%3E%3C/polygon%3E%3C/svg%3E");
      animation: spin 15s linear infinite;
    }
    
    .aiChat-icon-2 {
      bottom: 10px;
      right: 10px;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpath d='M12 8l4 4-4 4'%3E%3C/path%3E%3Cpath d='M8 12h8'%3E%3C/path%3E%3C/svg%3E");
      animation: spin 12s linear infinite reverse;
    }
    
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    
    .aiChat-tooltip-close {
      position: absolute;
      top: 8px;
      right: 8px;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      opacity: 0.7;
      transition: all 0.2s ease;
      border-radius: 50%;
      z-index: 10;
    }
    
    .aiChat-tooltip-close:hover {
      opacity: 1;
      background: rgba(255, 255, 255, 0.3);
      transform: rotate(90deg);
    }
    
    .aiChat-tooltip-close:before,
    .aiChat-tooltip-close:after {
      content: '';
      position: absolute;
      width: 12px;
      height: 2px;
      background-color: white;
      transition: all 0.3s ease;
    }
    
    .aiChat-tooltip-close:before {
      transform: rotate(45deg);
    }
    
    .aiChat-tooltip-close:after {
      transform: rotate(-45deg);
    }
    
    .aiChat-tooltip-progress {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 3px;
      background: rgba(255, 255, 255, 0.5);
      width: 100%;
      transform-origin: left;
      animation: progress 5s linear forwards;
    }
    
    @keyframes progress {
      from { transform: scaleX(1); }
      to { transform: scaleX(0); }
    }
    
    @keyframes float {
      0%, 100% { transform: translateY(0px); }
      50% { transform: translateY(-8px); }
    }
    
    @keyframes pulse {
      0%, 100% { opacity: 0.6; }
      50% { opacity: 1; }
    }
    
    @keyframes moveRight {
      0%, 100% { transform: translateX(0) rotate(-45deg); }
      50% { transform: translateX(10px) rotate(-45deg); }
    }
    
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px) scale(0.9); }
      to { opacity: 1; transform: translateY(0) scale(1); }
    }
    
    @keyframes fadeOut {
      from { opacity: 1; transform: translateY(0) scale(1); }
      to { opacity: 0; transform: translateY(20px) scale(0.9); }
    }
    
    @keyframes highlight {
      0% { box-shadow: 0 0 0 0 rgba(99, 230, 190, 0.4); }
      70% { box-shadow: 0 0 0 10px rgba(99, 230, 190, 0); }
      100% { box-shadow: 0 0 0 0 rgba(99, 230, 190, 0); }
    }
    
    .pulse-animation {
      animation: highlight 2s infinite;
    }
  `;
  document.head.appendChild(tooltipStyle);

  // 创建容器元素
  const container = document.createElement("div");
  container.className = "aiChat-tooltip-container";

  // 创建提示元素
  const tooltip = document.createElement("div");
  tooltip.className = "aiChat-tooltip pulse-animation";
  tooltip.innerHTML = `
    <div class="aiChat-tooltip-icon aiChat-icon-1"></div>
    <div class="aiChat-tooltip-icon aiChat-icon-2"></div>
    <div class="aiChat-tooltip-title">AIChat吉PT</div>
    <div class="aiChat-tooltip-text">
      将鼠标移动到屏幕右侧边缘<br>即可打开智能助手
    </div>
    <div class="aiChat-tooltip-progress"></div>
    <div class="aiChat-tooltip-close"></div>
  `;
  container.appendChild(tooltip);
  document.body.appendChild(container);

  // 创建箭头元素
  const arrow = document.createElement("div");
  arrow.className = "aiChat-tooltip-arrow";
  document.body.appendChild(arrow);

  // 关闭按钮点击事件
  const closeBtn = tooltip.querySelector(".aiChat-tooltip-close");
  closeBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    closeTooltip();
  });

  // 点击提示可以关闭
  tooltip.addEventListener("click", () => {
    closeTooltip();
  });

  // 关闭提示的函数
  function closeTooltip() {
    container.style.animation = "fadeOut 0.5s ease forwards";
    arrow.style.animation = "fadeOut 0.5s ease forwards";

    setTimeout(() => {
      container.remove();
      arrow.remove();
    }, 500);
  }

  // 5秒后自动消失
  setTimeout(() => {
    closeTooltip();
  }, 5000);
}

/**
 * Creates the main AI panel container
 * @returns {HTMLElement} The created container
 */
function createAiPanel() {
  const aiDivMain = document.createElement("div");
  aiDivMain.id = "aiDivMain";

  return aiDivMain;
}

/**
 * Creates the AI tool selection component
 * @returns {HTMLElement} The created component
 */
function createAiTool() {
  const aiTool = document.createElement("div");
  aiTool.id = "aiTool";

  return aiTool;
}

/**
 * Creates the model selector dropdown
 * @returns {HTMLElement} The created selector
 */
function createModelSelector() {
  const selectBox = document.createElement("select");
  selectBox.id = "selectBox";
  selectBox.style = `
      width: 100%;
      padding: 8px 10px;
      border-radius: 10px;
      background-color: rgba(69, 69, 69, 0.7);
      color: #ffffff;
      border: 1px solid rgba(255, 255, 255, 0.1);
  `;

  const option7 = document.createElement("option");
  option7.id = "option7";
  option7.value = "1a2b3c4d5e6f7g8h9i0j1k2l3m";
  option7.textContent = "Gemini-2.0-flash";

  const option11 = document.createElement("option");
  option11.id = "option11";
  option11.value = "7n8o9p0q1r2s3t4u5v6w";
  option11.textContent = "Grok-3-mini";

  const option12 = document.createElement("option");
  option12.id = "option12";
  option12.value = "65ba602fb62cs2d4dd42355c";
  option12.textContent = "Deepseek-R1";

  const option13 = document.createElement("option");
  option13.id = "option13";
  option13.value = "3a5b9c2d8e4f7g1h0i6j2k3l";
  option13.textContent = "Deepseek-V3-0324";

  selectBox.appendChild(option7);
  selectBox.appendChild(option11);
  selectBox.appendChild(option12);
  selectBox.appendChild(option13);

  return selectBox;
}

/**
 * Creates the AI output container
 * @returns {HTMLElement} The created container
 */
function createAiOutputContainer() {
  const aiDiv2 = document.createElement("div");
  aiDiv2.id = "aiDiv2";
  aiDiv2.style = `
      border-radius: 12px;
      z-index: 1000;
      background-color: rgba(50, 50, 50, 0.6);
      padding: 15px;
      user-select: text;
      display: block;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.05);
      transition: all 0.2s ease;
      flex: 1;
      min-height: 200px;
      max-height: calc(-115px + 100vh);
      overflow-y: auto;
  `;

  // Add chat output with modern welcome message
  const chat = document.createElement("div");
  chat.id = "chat";
  chat.style.color = "white";

  // 创建更现代的欢迎界面
  const welcomeHTML = `
    <div class="chat-welcome">
      <div class="welcome-header">
        <div class="welcome-logo">AI<span>Chat吉PT</span></div>
        <div class="welcome-subtitle">智能助手</div>
      </div>
      
      <div class="user-greeting-large">
        <div class="user-avatar">
          <div class="user-avatar-inner"></div>
          <div class="user-status-indicator"></div>
        </div>
        <div class="greeting-message">
          <div class="greeting-time"></div>
          <h2>您好，欢迎使用Chat吉PT！</h2>
          <p>很高兴为您提供帮助，请问有什么可以协助您的？</p>
        </div>
      </div>
      
     
    </div>
  `;

  chat.innerHTML = welcomeHTML;
  aiDiv2.appendChild(chat);

  // 初始化欢迎界面，设置问候时间
  setTimeout(() => {
    initializeWelcomeGreeting();
  }, 100);

  return aiDiv2;
}

/**
 * 初始化欢迎界面中的问候语和时间
 */
function initializeWelcomeGreeting() {
  const greetingTimeElement = document.querySelector(".greeting-time");
  if (greetingTimeElement) {
    // 设置时间
    const now = new Date();
    const timeOptions = { hour: "2-digit", minute: "2-digit" };
    let timeString = now.toLocaleTimeString(undefined, timeOptions);

    // 获取日期信息
    const dateOptions = { month: "long", day: "numeric", weekday: "long" };
    const dateString = now.toLocaleDateString(undefined, dateOptions);

    // 根据时间生成问候语
    let greeting = "早上好";
    const hours = now.getHours();

    if (hours >= 5 && hours < 11) {
      greeting = "早上好";
    } else if (hours >= 11 && hours < 13) {
      greeting = "中午好";
    } else if (hours >= 13 && hours < 18) {
      greeting = "下午好";
    } else {
      greeting = "晚上好";
    }

    // 生成带有日期的完整问候语
    greetingTimeElement.textContent = `${greeting}，${dateString} · ${timeString}`;

    // 临时设置用户信息为默认状态
    displayUserInfo(
      {
        nickname: "岛民",
        avatar: null,
        followerNum: 0,
        avatarFrame: null,
      },
      greeting
    );

    // 从API获取用户信息
    fetchUserInfo()
      .then((userData) => {
        if (userData && userData.code === 200 && userData.data) {
          // 使用API返回的用户数据更新界面
          displayUserInfo(
            {
              nickname: userData.data.nickname,
              avatar: userData.data.avatar || userData.data.previewUrl,
              followerNum: 0, // API返回中没有followerNum，设为0
              avatarFrame: userData.data.avatarFrame,
            },
            greeting
          );
        }
      })
      .catch((error) => {
        console.error("获取用户数据失败:", error);
      });
  }
}

/**
 * 从API获取用户信息
 * @returns {Promise} 包含用户数据的Promise
 */
async function fetchUserInfo() {
  try {
    // 获取授权令牌
    const authorization = unsafeWindow.box3EditCore.brpc.headers.auth;

    if (!authorization) {
      console.error("未找到授权令牌");
      return null;
    }

    // 调用API获取用户信息
    const response = await fetch("https://code-api-pc.dao3.fun/auth/user", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: authorization,
      },
    });

    const data = await response.json();
    return data;
  } catch (error) {
    console.error("调用API失败:", error);
    throw error;
  }
}

/**
 * 显示用户信息
 * @param {Object} userInfo - 用户信息对象
 * @param {string} greeting - 问候语
 */
function displayUserInfo(userInfo, greeting) {
  const userName = userInfo.nickname || "岛民";
  const userAvatar = userInfo.avatar;
  const userFollowers = userInfo.followerNum || 0;
  const hasAvatarFrame = Boolean(userInfo.avatarFrame);

  // 更新头像和用户问候语
  const userAvatarElement = document.querySelector(".user-avatar-inner");
  const greetingHeader = document.querySelector(".greeting-message h2");
  const userStatusIndicator = document.querySelector(".user-status-indicator");

  // 设置用户头像
  if (userAvatarElement) {
    if (userAvatar) {
      // 如果有头像，设置背景图片
      const img = new Image();
      img.onload = function () {
        userAvatarElement.style.backgroundImage = `url('${userAvatar}')`;
        userAvatarElement.textContent = "";
        userAvatarElement.classList.add("avatar-loaded");

        // 如果有头像框，添加特殊样式
        if (hasAvatarFrame) {
          userAvatarElement.style.borderColor = "rgba(255, 215, 0, 0.5)";
          userAvatarElement.style.boxShadow = "0 0 15px rgba(255, 215, 0, 0.3)";
        }
      };
      img.onerror = function () {
        // 头像加载失败，显示用户名首字母
        userAvatarElement.textContent = userName.charAt(0);
      };
      img.src = userAvatar;
    } else {
      // 如果没有头像，显示用户名首字母
      userAvatarElement.textContent = userName.charAt(0);
    }
  }

  // 更新状态指示器
  if (userStatusIndicator && userFollowers > 0) {
    userStatusIndicator.title = `${userFollowers} 个关注者`;

    // 根据关注者数量调整指示器颜色
    if (userFollowers > 100) {
      userStatusIndicator.style.backgroundColor = "#FFD700"; // 金色
    } else if (userFollowers > 50) {
      userStatusIndicator.style.backgroundColor = "#C0C0C0"; // 银色
    }
  }

  if (greetingHeader) {
    // 更新个性化问候语
    greetingHeader.textContent = `${greeting}，${userName}！`;
  }

  // 添加激励短语
  const motivationalPhrases = [
    "今天也要加油哦！",
    "有什么可以帮到您？",
    "需要编程帮助吗？",
    "代码问题我来解决！",
    "Let's make coding easier!",
    "有问题尽管问我",
    "我随时为您提供帮助",
  ];

  // 随机选择一个激励短语
  const randomPhrase =
    motivationalPhrases[Math.floor(Math.random() * motivationalPhrases.length)];
  const greetingMessage = document.querySelector(".greeting-message p");

  if (greetingMessage) {
    greetingMessage.textContent = randomPhrase;
  }
}

/**
 * Creates the input container for the chat
 * @returns {HTMLElement} The created container
 */
function createInputContainer() {
  const buttondiv = document.createElement("div");
  buttondiv.id = "buttondiv";
  buttondiv.style = `
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px 20px;
      background-color: rgba(40, 40, 40, 0.85);
      box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.15);
      border-top: 1px solid rgba(255, 255, 255, 0.05);
      z-index: 1002;
      position: sticky;
      bottom: 0;
  `;
  return buttondiv;
}

/**
 * Creates the chat input field
 * @param {Function} chatCustomizeRunner - Function to handle custom chat inputs
 * @returns {HTMLElement} The created input field
 */
function createChatInput(chatCustomizeRunner) {
  const input = document.createElement("input");
  input.placeholder = "请输入您的问题，也可以框选代码片段 (按Enter发送)";
  input.id = "chatjptI";
  input.autocomplete = "off";
  input.maxlength = "10000";
  input.style = `
      padding-left: 18px;
      margin-right: 10px;
      width: 100%;
      height: 42px;
      border-radius: 21px;
      z-index: 1001;
      background-color: rgba(28, 28, 28, 0.77);
      color: #ffffff;
      border: 1px solid rgba(100, 100, 100, 0.3);
      font-size: 14px;
      transition: all 0.2s ease;
  `;
  return input;
}

/**
 * Creates the chat button
 * @returns {HTMLElement} The created button
 */
function createButton() {
  const button = document.createElement("div");
  button.innerText = "吉PT";
  button.id = "chatjptT";
  button.style = `
      padding-left: 10px;
      padding-right: 10px;
      width: 120px;
      z-index: 1001;
      background-color: transparent;
      color: white;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: center;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      font-size: 13px;
      background: linear-gradient(90deg, #4d8af0, #63e6be);
      -webkit-background-clip: text;
      background-clip: text;
      -webkit-text-fill-color: transparent;
  `;
  return button;
}

/**
 * Appends all UI elements to their proper parent elements
 * @param {Object} elements - The UI elements to append
 */
function appendUIElements(elements) {
  // Append to #__next__root
  $("#__next__root").append(elements.aiDivMain);

  // Create a main container for chat content
  const chatMainContainer = document.createElement("div");
  chatMainContainer.id = "chat-main-container";
  $("#aiDivMain").append(chatMainContainer);

  $("#chat-main-container").append(elements.aiDiv2);

  // Append input area directly to aiDivMain (bottom)
  $("#aiDivMain").append(elements.buttondiv);

  // Append to buttondiv
  $("#buttondiv").append(elements.chatInput);
  $("#buttondiv").append(elements.aiTool);

  // Append to aiTool
  $("#aiTool").append(elements.selectBox);
}

/**
 * Sets up event listeners for the UI components
 * @param {Object} elements - The UI elements to attach listeners to
 * @param {Function} chatCustomizeRunner - Function to handle custom chat inputs
 */
function setupEventListeners(elements, chatCustomizeRunner) {
  // Mouse enter/leave events for the AI panel
  elements.aiDivMain.addEventListener("mouseenter", function () {
    elements.aiDivMain.style.right = "0";
    elements.aiDivMain.style.backgroundColor = "rgba(56, 56, 56, 0.95)";
    elements.aiDivMain.style.boxShadow = "0 5px 25px rgba(0, 0, 0, 0.3)";
  });

  elements.aiDivMain.addEventListener("mouseleave", function () {
    if (!hasFocus(elements.chatInput)) {
      elements.aiDivMain.style.right = "-750px";
      elements.aiDivMain.style.backgroundColor = "#3838384d";
      elements.aiDivMain.style.boxShadow = "#00000000 0px 0px 12px 0px";
    }
  });

  elements.aiDiv2.addEventListener("mouseenter", function () {
    this.style.boxShadow = "0 4px 12px rgba(0, 0, 0, 0.15)";
    this.style.borderColor = "rgba(255, 255, 255, 0.1)";
  });

  elements.aiDiv2.addEventListener("mouseleave", function () {
    this.style.boxShadow = "0 2px 8px rgba(0, 0, 0, 0.1)";
    this.style.borderColor = "rgba(255, 255, 255, 0.05)";
  });

  // Add scroll handling for aiDiv2
  elements.aiDiv2.addEventListener("scroll", function () {
    // Check if scrolled from bottom
    const isScrolled =
      this.scrollHeight - this.scrollTop - this.clientHeight > 20;
    if (isScrolled) {
      this.classList.add("scrolled");
    } else {
      this.classList.remove("scrolled");
    }
  });

  // Focus effect for chat input
  elements.chatInput.addEventListener("focus", function () {
    elements.buttondiv.style.backgroundColor = "rgba(45, 45, 45, 0.95)";
    elements.buttondiv.style.boxShadow = "0 -4px 15px rgba(0, 0, 0, 0.2)";
    this.style.borderColor = "#4d8af0";
    this.style.boxShadow = "0 0 0 3px rgba(77, 138, 240, 0.2)";
  });

  elements.chatInput.addEventListener("blur", function () {
    elements.buttondiv.style.backgroundColor = "rgba(40, 40, 40, 0.85)";
    elements.buttondiv.style.boxShadow = "0 -4px 12px rgba(0, 0, 0, 0.15)";
    this.style.borderColor = "rgba(100, 100, 100, 0.3)";
    this.style.boxShadow = "none";
  });

  // Set up global key listener for Enter
  window.addEventListener("keydown", function (event) {
    if (event.key === "Enter") {
      if (hasFocus(elements.chatInput)) {
        if (!event.shiftKey) {
          const inputValue = elements.chatInput.value.trim();
          if (inputValue) {
            // Add loading animation
            const chat = document.getElementById("chat");
            const userQuestion = `<div class="user-question">${inputValue}</div>`;
            chat.innerHTML =
              userQuestion +
              `
              <div class="ai-response">
                <strong>Chat吉PT：</strong>
                <div class="ai-thinking">
                  <div class="dot-typing"></div>
                  <div class="thinking-text">正在思考分析中...</div>
                </div>
              </div>
            `;

            // Call the chat function
            chatCustomizeRunner(200, inputValue);
            elements.chatInput.value = "";
            elements.chatInput.blur();

            // Scroll the aiDiv2 container to show the latest message
            document.getElementById("aiDiv2").scrollTop =
              document.getElementById("aiDiv2").scrollHeight;
            // Check if need to show gradient
            elements.aiDiv2.classList.remove("scrolled");
          }
        }
      }
    }
  });
}

/**
 * Shows the AI panel
 * @param {Object} elements - The UI elements
 */
export function showAiPanel(elements) {
  elements.aiDivMain.style.right = "0";
  elements.aiDivMain.style.backgroundColor = "rgba(56, 56, 56, 0.95)";
  elements.aiDivMain.style.boxShadow = "0 5px 25px rgba(0, 0, 0, 0.3)";

  // Update the greeting message with current time
  initializeWelcomeGreeting();

  // Focus the input field when panel appears
  setTimeout(() => {
    elements.chatInput.focus();
  }, 300);

  // Ensure scrolling to bottom of the chat container
  if (document.getElementById("aiDiv2")) {
    document.getElementById("aiDiv2").scrollTop =
      document.getElementById("aiDiv2").scrollHeight;
  }
}

/**
 * Updates the chat UI with new content
 * @param {string} chatContent - The new content to display
 */
export function updateChatContent(chatContent) {
  // Add insert code buttons to pre elements,但排除用户代码预览部分
  const pres = $("#chat").find("pre").not(".selected-code pre");
  const btn = `<span class="code-insert-btn" onclick='editObk.getModel().applyEdits([{range:editObk.getSelection(),text:$(this).parent().text().replace("插入代码","")}]);'>插入代码</span>`;
  pres.each(function () {
    // 避免重复添加按钮
    if ($(this).find(".code-insert-btn").length === 0) {
      $(this).prepend(btn);
    }
  });

  // Apply syntax highlighting to all code blocks
  hljs.highlightAll();

  // 确保代码块中的复制按钮正常工作
  $(".code-insert-btn").on("click", function (e) {
    e.stopPropagation();
    // 获取代码内容
    const codeText = $(this).parent().find("code").text();
    // 应用到编辑器
    if (unsafeWindow.editObk && unsafeWindow.editObk.getModel()) {
      unsafeWindow.editObk.getModel().applyEdits([
        {
          range: unsafeWindow.editObk.getSelection(),
          text: codeText,
        },
      ]);
    }
  });

  // Scroll to bottom of the chat container to show latest content
  if (document.getElementById("aiDiv2")) {
    const chatContainer = document.getElementById("aiDiv2");
    chatContainer.scrollTop = chatContainer.scrollHeight;

    // Reset scrolled state
    chatContainer.classList.remove("scrolled");
  }
}

/**
 * Updates the chat header with user information
 * @param {Object} user - The user information to display
 */
export function updateChatHeader(user) {
  $("#chatq").html(
    `<div class="user-greeting">欢迎，<span class="user-name">${user.data.nickname}</span></div>`
  );
}

// Add a CSS rule for welcome footer styling
const style = document.createElement("style");
style.textContent = `
  .welcome-footer {
    margin-top: 20px;
    text-align: center;
    color: #b3b3b3;
    font-size: 13px;
    padding: 10px;
    border-top: 1px solid rgba(100, 100, 100, 0.2);
  }
`;
document.head.appendChild(style);

/**
 * 创建代码包弹出界面
 */
function createCodePackageModal() {
  // 检查是否已存在
  if (document.getElementById("code-package-modal")) {
    return document.getElementById("code-package-modal");
  }

  // 创建弹出框
  const modal = document.createElement("div");
  modal.id = "code-package-modal";
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(5px);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s, visibility 0.3s;
  `;

  // 创建内容容器
  const modalContent = document.createElement("div");
  modalContent.className = "code-package-modal-content";
  modalContent.style.cssText = `
    width: 80%;
    max-width: 1200px;
    max-height: 95%;
    background-color: rgba(38, 38, 38, 0.95);
    border-radius: 16px;
    padding: 25px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    border: 1px solid rgba(255, 255, 255, 0.1);
    animation: modalGlow 3s infinite alternate;
  `;

  // 添加头部装饰
  const headerDecoration = document.createElement("div");
  headerDecoration.style.cssText = `
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #4d8af0, #63e6be);
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
  `;
  modalContent.appendChild(headerDecoration);

  // 创建标题
  const header = document.createElement("div");
  header.style.cssText = `
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  `;

  const title = document.createElement("h2");
  title.textContent = "代码包列表";
  title.style.cssText = `
    margin: 0;
    color: #ffffff;
    font-size: 22px;
    font-weight: 500;
    display: flex;
    align-items: center;
  `;

  // 添加标题图标
  const titleIcon = document.createElement("div");
  titleIcon.style.cssText = `
    width: 28px;
    height: 28px;
    margin-right: 12px;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%234d8af0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='16 18 22 12 16 6'%3E%3C/polyline%3E%3Cpolyline points='8 6 2 12 8 18'%3E%3C/polyline%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-size: contain;
  `;
  title.prepend(titleIcon);

  // 创建投稿按钮
  const submitButton = document.createElement("button");
  submitButton.textContent = "投稿";
  submitButton.style.cssText = `
    background-color: rgba(99, 230, 190, 0.2);
    color: #63e6be;
    border: 1px solid rgba(99, 230, 190, 0.3);
    border-radius: 6px;
    padding: 6px 16px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    margin-left: 15px;
    display: flex;
    align-items: center;
  `;

  // 添加投稿图标
  const uploadIcon = document.createElement("span");
  uploadIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>`;
  uploadIcon.style.cssText = `
    margin-right: 8px;
  `;
  submitButton.prepend(uploadIcon);

  submitButton.addEventListener("mouseover", () => {
    submitButton.style.backgroundColor = "rgba(99, 230, 190, 0.3)";
    submitButton.style.transform = "translateY(-2px)";
  });

  submitButton.addEventListener("mouseout", () => {
    submitButton.style.backgroundColor = "rgba(99, 230, 190, 0.2)";
    submitButton.style.transform = "translateY(0)";
  });

  submitButton.addEventListener("click", () => {
    showSubmitModal();
  });

  // 添加投稿按钮到标题旁边
  const titleContainer = document.createElement("div");
  titleContainer.style.cssText = `
    display: flex;
    align-items: center;
  `;
  titleContainer.appendChild(title);
  titleContainer.appendChild(submitButton);

  // 创建关闭按钮
  const closeButton = document.createElement("div");
  closeButton.innerHTML = "&times;";
  closeButton.style.cssText = `
    font-size: 28px;
    color: #aaa;
    cursor: pointer;
    transition: color 0.2s;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  `;
  closeButton.addEventListener("mouseover", () => {
    closeButton.style.color = "#fff";
    closeButton.style.backgroundColor = "rgba(255, 255, 255, 0.1)";
  });
  closeButton.addEventListener("mouseout", () => {
    closeButton.style.color = "#aaa";
    closeButton.style.backgroundColor = "transparent";
  });
  closeButton.addEventListener("click", () => {
    hideModal(modal);
  });

  // 创建搜索区域容器
  const searchContainer = document.createElement("div");
  searchContainer.style.cssText = `
    margin-bottom: 20px;
    padding: 0 5px;
    position: relative;
  `;

  // 创建搜索框
  const searchBox = document.createElement("input");
  searchBox.type = "text";
  searchBox.placeholder = "搜索代码包名/简介...";
  searchBox.style.cssText = `
    width: 100%;
    padding: 12px 15px 12px 42px;
    background-color: rgba(30, 30, 30, 0.7);
    color: #fff;
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    font-size: 14px;
    outline: none;
    transition: all 0.3s ease;
    box-sizing: border-box;
  `;

  // 搜索框焦点效果
  searchBox.addEventListener("focus", () => {
    searchBox.style.backgroundColor = "rgba(40, 40, 40, 0.8)";
    searchBox.style.borderColor = "rgba(77, 138, 240, 0.5)";
    searchBox.style.boxShadow = "0 0 0 3px rgba(77, 138, 240, 0.15)";
  });

  searchBox.addEventListener("blur", () => {
    searchBox.style.backgroundColor = "rgba(30, 30, 30, 0.7)";
    searchBox.style.borderColor = "rgba(255, 255, 255, 0.1)";
    searchBox.style.boxShadow = "none";
  });

  // 创建搜索图标
  const searchIcon = document.createElement("div");
  searchIcon.style.cssText = `
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: center;
    pointer-events: none;
    opacity: 0.7;
  `;

  // 创建清除按钮
  const clearButton = document.createElement("div");
  clearButton.style.cssText = `
    position: absolute;
    right: 15px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='15' y1='9' x2='9' y2='15'%3E%3C/line%3E%3Cline x1='9' y1='9' x2='15' y2='15'%3E%3C/line%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: center;
    cursor: pointer;
    display: none;
    opacity: 0.7;
    transition: opacity 0.2s ease;
  `;

  clearButton.addEventListener("mouseover", () => {
    clearButton.style.opacity = "1";
  });

  clearButton.addEventListener("mouseout", () => {
    clearButton.style.opacity = "0.7";
  });

  clearButton.addEventListener("click", () => {
    searchBox.value = "";
    clearButton.style.display = "none";
    // 显示所有卡片
    filterCodePackages("");
  });

  // 搜索框输入事件
  searchBox.addEventListener("input", (e) => {
    const searchValue = e.target.value.trim();
    clearButton.style.display = searchValue.length > 0 ? "block" : "none";
    filterCodePackages(searchValue);
  });

  // 将搜索元素添加到搜索容器
  searchContainer.appendChild(searchIcon);
  searchContainer.appendChild(searchBox);
  searchContainer.appendChild(clearButton);

  // 创建包列表容器
  const packageListContainer = document.createElement("div");
  packageListContainer.style.cssText = `
    overflow-y: auto;
    flex: 1;
    padding: 5px 10px;
    margin-right: -10px;
  `;

  // 为包列表创建瀑布流布局
  const packageList = document.createElement("div");
  packageList.style.cssText = `
    column-count: 3;
    column-gap: 20px;
    width: 100%;
  `;

  // 添加响应式列数
  const responsiveStyleElement = document.createElement("style");
  responsiveStyleElement.textContent = `
    @media (max-width: 1200px) {
      #code-package-modal .code-package-modal-content > div > div[style*="column-count"] {
        column-count: 2 !important;
      }
    }
    @media (max-width: 768px) {
      #code-package-modal .code-package-modal-content > div > div[style*="column-count"] {
        column-count: 1 !important;
      }
    }
  `;
  document.head.appendChild(responsiveStyleElement);

  // 创建无结果提示
  const noResultsMessage = document.createElement("div");
  noResultsMessage.style.cssText = `
    display: none;
    width: 100%;
    text-align: center;
    color: #aaa;
    padding: 40px 20px;
    font-size: 15px;
    column-span: all;
  `;
  noResultsMessage.innerHTML = `
    <div style="margin-bottom: 15px;">
      <svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#aaa" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="11" cy="11" r="8"></circle>
        <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
        <line x1="11" y1="8" x2="11" y2="14"></line>
        <line x1="8" y1="11" x2="14" y2="11"></line>
      </svg>
    </div>
    <div style="font-weight: 500; margin-bottom: 8px;">未找到相关代码包</div>
    <div style="font-size: 13px; opacity: 0.8;">请尝试使用不同的关键词搜索</div>
  `;
  packageList.appendChild(noResultsMessage);

  // 从API获取代码包数据
  let codePackages = [];

  // 立即加载并显示代码包
  fetchCodePackages()
    .then((data) => {
      codePackages = data;
      renderCodePackages(codePackages);
    })
    .catch((error) => {
      console.error("获取代码包失败:", error);
      showNotification("获取代码包数据失败", "error");
    });

  /**
   * 从API获取代码包数据
   * @returns {Promise<Array>} 代码包数据数组
   */
  async function fetchCodePackages() {
    try {
      const response = await fetch(
        "https://api.box3lab.com/dao3lab/get_codepackage"
      );
      if (!response.ok) {
        throw new Error(`API响应错误: ${response.status}`);
      }

      const data = await response.json();

      // 处理API返回的数据格式
      return data.map((pkg) => {
        // 确定导入类型
        let importType = pkg.isClient === 1 ? "client" : "server"; // 默认为服务端
        if (pkg.isConsole === 1) {
          importType = "console";
        }

        // 处理type字段，只保留/-/后面的部分
        let cleanType = pkg.type;
        if (pkg.type && pkg.type.includes("/-/")) {
          cleanType = pkg.type.split("/-/")[1];
        }

        return {
          id: pkg.uid,
          title: pkg.title,
          description: pkg.doc || "暂无描述",
          code: "", // 代码内容将在用户选择导入时从URL获取
          codeUrl: pkg.url,
          docUrl: pkg.help,
          importType: importType,
          isClient: pkg.isClient,
          type: cleanType,
          time: pkg.time,
        };
      });
    } catch (error) {
      console.error("获取代码包失败:", error);
      return [];
    }
  }

  /**
   * 渲染代码包到界面
   * @param {Array} packages - 代码包数据数组
   */
  function renderCodePackages(packages) {
    // 清空现有内容
    packageList.innerHTML = "";

    // 过滤掉没有标题的代码包
    packages = packages.filter((pkg) => pkg.title && pkg.title.trim() !== "");

    // 如果没有代码包，显示无结果消息
    if (packages.length === 0) {
      noResultsMessage.style.display = "block";
      return;
    }

    // 按时间倒序排序，最新的排在前面
    packages.sort((a, b) => {
      const timeA = a.time ? parseInt(a.time) : 0;
      const timeB = b.time ? parseInt(b.time) : 0;
      return timeB - timeA;
    });

    // 渲染每个代码包
    packages.forEach((pkg) => {
      // 创建一个随机的最小高度变化，增强瀑布流效果
      const randomHeight = Math.floor(Math.random() * 50) + 150;

      const card = document.createElement("div");
      card.className = "code-package-card";
      card.style.cssText = `
        background-color: rgba(40, 40, 40, 0.7);
        border-radius: 12px;
        overflow: hidden;
        transition: all 0.3s ease;
        border: 1px solid rgba(255, 255, 255, 0.05);
        padding: 0;
        position: relative;
        display: inline-block;
        width: 100%;
        margin-bottom: 20px;
        break-inside: avoid;
        min-height: ${randomHeight}px;
      `;

      // 存储包数据引用以用于搜索
      card.packageData = pkg;

      // 卡片内容
      const cardContent = document.createElement("div");
      cardContent.style.cssText = `
        padding: 20px;
        display: flex;
        flex-direction: column;
        height: 100%;
        box-sizing: border-box;
      `;

      // 标题
      const title = document.createElement("h3");
      title.textContent = pkg.title;
      title.style.cssText = `
        margin: 0;
        font-size: 17px;
        font-weight: 500;
        color: #fff;
        flex: 1;
      `;

      // 显示导入类型标签
      const importTypeLabel = document.createElement("div");
      importTypeLabel.style.cssText = `
        display: inline-block;
        font-size: 11px;
        padding: 3px 8px;
        border-radius: 10px;
        font-weight: 500;
        white-space: nowrap;
        margin-left: 10px;
      `;

      // 根据导入类型设置不同样式
      switch (pkg.importType) {
        case "console":
          importTypeLabel.textContent = "控制台";
          importTypeLabel.style.backgroundColor = "rgb(255 60 60 / 20%)";
          importTypeLabel.style.color = "rgb(255 60 60)";
          importTypeLabel.style.border = "1px solid rgba(255, 60, 60, 0.3)";
          break;
        case "server":
          importTypeLabel.textContent = "服务端";
          importTypeLabel.style.backgroundColor = "rgb(209 83 231 / 20%)";
          importTypeLabel.style.color = "rgb(206 60 231)";
          break;
        case "client":
          importTypeLabel.textContent = "客户端";
          importTypeLabel.style.backgroundColor = "rgb(83 231 199 / 20%)";
          importTypeLabel.style.color = "rgb(83 231 199)";
          break;
      }

      // 创建标题行容器
      const titleRow = document.createElement("div");
      titleRow.style.cssText = `
        display: flex;
        align-items: center;
        margin-bottom: 12px;
      `;

      titleRow.appendChild(title);
      titleRow.appendChild(importTypeLabel);

      // 描述
      const desc = document.createElement("div");
      desc.className = "code-package-description";
      desc.style.cssText = `
        color: #aaa;
        margin: 10px 0 20px;
        font-size: 13px;
        flex-grow: 1;
        line-height: 1.5;
        white-space:pre-line;
      `;

      // 使用Markdown解析描述内容
      try {
        if (window.marked) {
          desc.innerHTML = marked.parse(pkg.description);

          // 为描述中的链接添加样式和目标
          const links = desc.querySelectorAll("a");
          links.forEach((link) => {
            link.style.cssText = `
              color: #4d8af0;
              text-decoration: none;
              border-bottom: 1px dotted #4d8af0;
            `;
            link.setAttribute("target", "_blank");
            link.setAttribute("rel", "noopener noreferrer");
          });
        } else {
          // 如果marked库未加载，回退到普通文本显示
          desc.style.whiteSpace = "pre-line";
          desc.textContent = pkg.description;
        }
      } catch (e) {
        // 解析出错时回退到普通文本
        desc.style.whiteSpace = "pre-line";
        desc.textContent = pkg.description;
        console.error("Markdown解析错误:", e);
      }

      // 卡片底部
      const cardFooter = document.createElement("div");
      cardFooter.style.cssText = `
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #888;
      `;

      // 添加发布时间
      const timestamp = document.createElement("div");
      timestamp.style.cssText = `
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #888;
      `;

      // 时间图标
      const timeIcon = document.createElement("div");
      timeIcon.style.cssText = `
        width: 14px;
        height: 14px;
        margin-right: 6px;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpolyline points='12 6 12 12 16 14'%3E%3C/polyline%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-size: contain;
      `;
      timestamp.appendChild(timeIcon);

      // 格式化时间戳
      let publishDate = "未知时间";
      if (pkg.time) {
        const date = new Date(pkg.time * 1000);
        publishDate = `${date.getFullYear()}-${String(
          date.getMonth() + 1
        ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
      }

      const timeText = document.createElement("span");
      timeText.textContent = publishDate;
      timestamp.appendChild(timeText);

      // 添加时间显示到底部
      cardFooter.appendChild(timestamp);

      if (/^https?:\/\//.test(pkg.docUrl)) {
        // 帮助按钮
        const helpBtn = document.createElement("button");
        helpBtn.textContent = "查看文档";
        helpBtn.style.cssText = `
        background-color: rgba(77, 138, 240, 0.2);
        color: #4d8af0;
        border: 1px solid rgba(77, 138, 240, 0.3);
        border-radius: 6px;
        padding: 8px 14px;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.2s ease;
        margin-left: auto;
      `;

        helpBtn.addEventListener("mouseover", () => {
          helpBtn.style.backgroundColor = "rgba(77, 138, 240, 0.3)";
          helpBtn.style.transform = "translateY(-2px)";
        });

        helpBtn.addEventListener("mouseout", () => {
          helpBtn.style.backgroundColor = "rgba(77, 138, 240, 0.2)";
          helpBtn.style.transform = "translateY(0)";
        });

        // 更新帮助按钮点击事件，打开文档URL
        helpBtn.addEventListener("click", (e) => {
          e.stopPropagation();
          window.open(pkg.docUrl, "_blank");
        });
        cardFooter.appendChild(helpBtn);
      }
      // 导入按钮
      const importBtn = document.createElement("button");
      importBtn.textContent = "导入";
      importBtn.className = "import-btn";
      importBtn.style.cssText = `
        background-color: rgba(99, 230, 190, 0.2);
        color: #63e6be;
        border: 1px solid rgba(99, 230, 190, 0.3);
        border-radius: 6px;
        padding: 8px 14px;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.2s ease;
        position: relative;
        margin-left: 10px;
      `;

      importBtn.addEventListener("mouseover", () => {
        importBtn.style.backgroundColor = "rgba(99, 230, 190, 0.3)";
        importBtn.style.transform = "translateY(-2px)";
      });

      importBtn.addEventListener("mouseout", () => {
        importBtn.style.backgroundColor = "rgba(99, 230, 190, 0.2)";
        importBtn.style.transform = "translateY(0)";
      });

      // 添加导入按钮点击事件
      importBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        try {
          // 使用pkgData的副本而不是引用
          const packageData = { ...pkg };
          showImportConfirmation(packageData, card);
        } catch (err) {
          console.error("导入按钮点击错误:", err);
          showNotification(
            "导入操作失败: " + (err.message || "未知错误"),
            "error"
          );
        }
      });

      cardFooter.appendChild(importBtn);

      // 将所有元素添加到卡片
      cardContent.appendChild(titleRow);
      cardContent.appendChild(desc);
      cardContent.appendChild(cardFooter);
      card.appendChild(cardContent);

      // 将卡片添加到列表
      packageList.appendChild(card);
    });
  }

  packageListContainer.appendChild(packageList);

  // 组装弹出窗口
  header.appendChild(titleContainer);
  header.appendChild(closeButton);
  modalContent.appendChild(header);
  modalContent.appendChild(searchContainer);
  modalContent.appendChild(packageListContainer);
  modal.appendChild(modalContent);

  // 添加点击外部关闭功能
  modal.addEventListener("click", (e) => {
    if (e.target === modal) {
      hideModal(modal);
    }
  });

  // 添加到文档
  document.body.appendChild(modal);

  // 添加CSS样式
  const styleElement = document.createElement("style");
  styleElement.textContent = `
    #code-package-modal::-webkit-scrollbar {
      width: 6px;
    }
    
    #code-package-modal::-webkit-scrollbar-track {
      background: rgba(30, 30, 30, 0.1);
    }
    
    #code-package-modal::-webkit-scrollbar-thumb {
      background: rgba(100, 100, 100, 0.3);
      border-radius: 3px;
    }
    
    #code-package-modal::-webkit-scrollbar-thumb:hover {
      background: rgba(120, 120, 120, 0.5);
    }
    
    .code-package-modal-content::-webkit-scrollbar {
      width: 6px;
    }
    
    .code-package-modal-content::-webkit-scrollbar-track {
      background: rgba(30, 30, 30, 0.1);
    }
    
    .code-package-modal-content::-webkit-scrollbar-thumb {
      background: rgba(100, 100, 100, 0.3);
      border-radius: 3px;
    }
    
    .code-package-confirm {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(30, 30, 30, 0.95);
      border-radius: 12px;
      padding: 20px;
      display: flex;
      flex-direction: column;
      z-index: 10;
      box-sizing: border-box;
    }
    
    @keyframes modalGlow {
      0% {
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
      }
      100% {
        box-shadow: 0 8px 32px rgba(77, 138, 240, 0.2);
      }
    }
  `;
  document.head.appendChild(styleElement);

  // 添加过滤代码包的功能
  function filterCodePackages(searchValue) {
    const searchLower = searchValue.toLowerCase();
    let visibleCount = 0;

    // 获取所有代码包卡片
    const cards = packageList.querySelectorAll(".code-package-card");

    cards.forEach((card) => {
      const pkg = card.packageData;
      if (!pkg) return;

      // 跳过没有标题的代码包
      if (!pkg.title || pkg.title.trim() === "") {
        card.style.display = "none";
        return;
      }

      // 检查搜索值是否匹配代码包名称、作者名、合作者名或描述
      const titleMatch = pkg.title.toLowerCase().includes(searchLower);

      // 检查描述
      const descriptionMatch = pkg.description
        .toLowerCase()
        .includes(searchLower);

      // 如果任何一项匹配，则显示卡片
      const shouldShow = titleMatch || descriptionMatch;

      card.style.display = shouldShow ? "block" : "none";
      if (shouldShow) visibleCount++;
    });

    // 显示或隐藏"无结果"消息
    noResultsMessage.style.display = visibleCount === 0 ? "block" : "none";
  }

  return modal;
}

/**
 * 显示弹出窗口
 */
function showModal(modal) {
  modal.style.visibility = "visible";
  modal.style.opacity = "1";
}

/**
 * 隐藏弹出窗口
 */
function hideModal(modal) {
  modal.style.opacity = "0";
  setTimeout(() => {
    modal.style.visibility = "hidden";
  }, 300);
}

/**
 * 添加代码包按钮到左侧菜单
 */
function addCodePackageButton() {
  // 查找左侧菜单
  const leftMenuNav = document.querySelector(".left-menu_navMode__kDHbk");
  if (!leftMenuNav) {
    console.log("无法找到左侧菜单");
    return;
  }

  // 创建代码包按钮
  const codePackageButton = document.createElement("div");
  codePackageButton.className = "left-menu_navItem__ZblIG";
  codePackageButton.innerHTML = `
    <div class="left-menu_navItemContent__2AzRh">
      <div class="left-menu_divider__RQwPt"></div>
      <div class="left-menu_titleItem__PhlmV">代码包</div>
    </div>
  `;

  // 添加点击事件
  codePackageButton.addEventListener("click", () => {
    const modal = createCodePackageModal();
    showModal(modal);
  });

  // 添加到左侧菜单
  leftMenuNav.appendChild(codePackageButton);
}

/**
 * 显示导入确认对话框
 * @param {Object} packageData - 代码包数据
 * @param {HTMLElement} packageCard - 代码包卡片元素
 */
function showImportConfirmation(packageData, packageCard) {
  // 创建全屏确认区域
  const modalOverlay = document.createElement("div");
  modalOverlay.className = "import-confirm-overlay";
  modalOverlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(5px);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 11000;
    animation: fadeIn 0.2s ease;
  `;

  // 创建确认对话框
  const confirmArea = document.createElement("div");
  confirmArea.className = "code-package-confirm";
  confirmArea.style.cssText = `
    width: 90%;
    max-width: 600px;
    background-color: rgba(35, 35, 35, 0.95);
    border-radius: 16px;
    padding: 30px;
    display: flex;
    flex-direction: column;
    position: relative;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(77, 138, 240, 0.3);
    max-height: 80vh;
    overflow: hidden;
  `;

  // 添加头部装饰条
  const headerDecoration = document.createElement("div");
  headerDecoration.style.cssText = `
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: ${
      packageData.importType === "console"
        ? "linear-gradient(90deg, #ff3c3c, #ff7070)"
        : "linear-gradient(90deg, #4d8af0, #63e6be)"
    };
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    z-index: 2;
  `;
  confirmArea.appendChild(headerDecoration);

  // 创建内容滚动区域
  const scrollableContent = document.createElement("div");
  scrollableContent.style.cssText = `
    flex: 1;
    overflow-y: auto;
    padding-right: 10px;
    margin-right: -10px;
    margin-bottom: 20px;
  `;
  confirmArea.appendChild(scrollableContent);

  // 包信息区域
  const packageInfoSection = document.createElement("div");
  packageInfoSection.style.cssText = `
    display: flex;
    margin-bottom: 25px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  
  `;

  // 包信息
  const packageInfo = document.createElement("div");
  packageInfo.style.cssText = `
    flex: 1;
  `;

  // 导入类型标签
  const importTypeLabel = document.createElement("div");
  importTypeLabel.style.cssText = `
    display: inline-block;
    font-size: 12px;
    padding: 3px 10px;
    border-radius: 12px;
    margin-bottom: 8px;
    font-weight: 500;
  `;

  // 根据导入类型设置不同样式
  switch (packageData.importType) {
    case "console":
      importTypeLabel.textContent = "控制台";
      importTypeLabel.style.backgroundColor = "rgba(255, 60, 60, 0.25)";
      importTypeLabel.style.color = "#ff7070";
      importTypeLabel.style.border = "1px solid rgba(255, 60, 60, 0.3)";
      break;
    case "server":
      importTypeLabel.textContent = "服务端";
      importTypeLabel.style.backgroundColor = "rgba(156, 39, 176, 0.2)";
      importTypeLabel.style.color = "#9c27b0";
      break;
    case "client":
      importTypeLabel.textContent = "客户端";
      importTypeLabel.style.backgroundColor = "rgba(33, 150, 243, 0.2)";
      importTypeLabel.style.color = "#2196f3";
      break;
  }
  packageInfo.appendChild(importTypeLabel);

  // 确认标题
  const confirmTitle = document.createElement("h2");
  confirmTitle.textContent = packageData.title;
  confirmTitle.style.cssText = `
    font-size: 22px;
    font-weight: 500;
    color: #fff;
    margin: 0 0 10px 0;
  `;
  packageInfo.appendChild(confirmTitle);

  packageInfoSection.appendChild(packageInfo);
  scrollableContent.appendChild(packageInfoSection);

  // 安全警告 - 对于控制台导入特别突出显示
  if (packageData.importType === "console") {
    const warningBox = document.createElement("div");
    warningBox.className = "import-warning-box";
    warningBox.style.cssText = `
      background-color: rgba(255, 60, 60, 0.2);
      border: 1px solid rgba(255, 60, 60, 0.4);
      border-radius: 6px;
      padding: 12px 15px;
      margin: 15px 0;
      color: #ffcccc;
      font-size: 13px;
    `;

    const warningIcon = document.createElement("div");
    warningIcon.style.cssText = `
      display: inline-block;
      width: 20px;
      height: 20px;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23ff3c3c' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z'%3E%3C/path%3E%3Cline x1='12' y1='9' x2='12' y2='13'%3E%3C/line%3E%3Cline x1='12' y1='17' x2='12.01' y2='17'%3E%3C/line%3E%3C/svg%3E");
      background-size: contain;
      background-repeat: no-repeat;
      vertical-align: middle;
      margin-right: 10px;
    `;

    const warningText = document.createElement("div");
    warningText.style.cssText = `
      display: inline-block;
      vertical-align: middle;
      width: calc(100% - 30px);
    `;
    warningText.innerHTML = `
      <strong>安全警告：</strong>控制台导入将直接执行代码，且<strong>无法撤销或回退</strong>。
      <ul style="margin: 8px 0 0 0; padding-left: 20px;">
        <li>请确保已备份您的项目</li>
        <li>代码包来自第三方创作者投稿，无法验证其安全性</li>
        <li>导入后的代码可能会修改您的项目或产生意外影响</li>
      </ul>
    `;

    warningBox.appendChild(warningIcon);
    warningBox.appendChild(warningText);
    scrollableContent.appendChild(warningBox);
  }

  // 导入选项 - 只在importType未指定或为console时显示选择
  if (packageData.importType === "console") {
    const optionsSection = document.createElement("div");
    optionsSection.style.cssText = `
      margin-bottom: 25px;
    `;

    const optionsTitle = document.createElement("div");
    optionsTitle.textContent = "导入选项";
    optionsTitle.style.cssText = `
      font-size: 14px;
      font-weight: 500;
      color: #ddd;
      margin-bottom: 12px;
    `;
    optionsSection.appendChild(optionsTitle);

    const optionsContainer = document.createElement("div");
    optionsContainer.style.cssText = `
      display: flex;
      flex-direction: column;
      gap: 12px;
      background-color: rgba(0, 0, 0, 0.1);
      padding: 15px;
      border-radius: 6px;
      border: 1px solid rgba(255, 255, 255, 0.05);
    `;

    // 控制台导入选项
    const consoleOption = createImportOption(
      "console-import",
      "控制台导入",
      "直接添加到控制台（不可回退！）",
      true
    );

    // 新脚本导入选项
    const scriptOption = createImportOption(
      "script-import",
      "新脚本导入",
      "创建新脚本文件（更安全的选择）",
      false
    );

    optionsContainer.appendChild(consoleOption);
    optionsContainer.appendChild(scriptOption);
    optionsSection.appendChild(optionsContainer);
    scrollableContent.appendChild(optionsSection);
  }

  // 包描述
  const descriptionSection = document.createElement("div");
  descriptionSection.style.cssText = `
    margin-bottom: 20px;
  `;

  const descriptionTitle = document.createElement("div");
  descriptionTitle.textContent = "包描述";
  descriptionTitle.style.cssText = `
    font-size: 14px;
    font-weight: 500;
    color: #ddd;
    margin-bottom: 8px;
  `;
  descriptionSection.appendChild(descriptionTitle);

  const descriptionText = document.createElement("div");
  descriptionText.style.cssText = `
    font-size: 14px;
    color: #ddd;
    line-height: 1.6;
    margin-bottom: 0;
    border-radius: 6px;
    border: 1px solid rgba(255, 255, 255, 0.05);
    padding: 12px;
    white-space:pre-line;
  `;

  // 使用Markdown解析描述内容
  try {
    if (window.marked) {
      descriptionText.innerHTML = marked.parse(packageData.description);

      // 为描述中的链接添加样式和目标
      const links = descriptionText.querySelectorAll("a");
      links.forEach((link) => {
        link.style.cssText = `
          color: #4d8af0;
          text-decoration: none;
          border-bottom: 1px dotted #4d8af0;
        `;
        link.setAttribute("target", "_blank");
        link.setAttribute("rel", "noopener noreferrer");
      });
    } else {
      // 如果marked库未加载，回退到普通文本显示
      descriptionText.style.whiteSpace = "pre-line";
      descriptionText.textContent = packageData.description;
    }
  } catch (e) {
    // 解析出错时回退到普通文本
    descriptionText.style.whiteSpace = "pre-line";
    descriptionText.textContent = packageData.description;
    console.error("Markdown解析错误:", e);
  }

  descriptionSection.appendChild(descriptionText);
  scrollableContent.appendChild(descriptionSection);

  // 代码预览区域
  const codePreviewSection = document.createElement("div");
  codePreviewSection.style.cssText = `
    margin-bottom: 25px;
  `;

  const codePreviewTitle = document.createElement("div");
  codePreviewTitle.textContent = "代码预览";
  codePreviewTitle.style.cssText = `
    font-size: 14px;
    font-weight: 500;
    color: #ddd;
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  `;

  const codeSnippetLink = document.createElement("a");
  codeSnippetLink.textContent = "折叠代码";
  codeSnippetLink.href = "#";
  codeSnippetLink.style.cssText = `
    font-size: 12px;
    color: #4d8af0;
    text-decoration: none;
  `;

  // Add the fullscreen button after the codeSnippetLink but before its click event:

  // 添加全屏预览按钮
  const fullscreenButton = document.createElement("a");
  fullscreenButton.href = "#";
  fullscreenButton.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path>
    </svg>
  `;
  fullscreenButton.style.cssText = `
    margin-left: 15px;
    color: #4d8af0;
    font-size: 12px;
    display: flex;
    align-items: center;
    text-decoration: none;
  `;

  // 添加全屏预览点击事件
  fullscreenButton.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();

    // 创建全屏遮罩
    const fullscreenOverlay = document.createElement("div");
    fullscreenOverlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.9);
      backdrop-filter: blur(5px);
      z-index: 12000;
      display: flex;
      flex-direction: column;
      padding: 40px;
      box-sizing: border-box;
    `;

    // 创建全屏预览头部
    const fullscreenHeader = document.createElement("div");
    fullscreenHeader.style.cssText = `
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    `;

    // 标题
    const fullscreenTitle = document.createElement("div");
    fullscreenTitle.textContent = `${packageData.title} - 代码预览`;
    fullscreenTitle.style.cssText = `
      font-size: 20px;
      font-weight: 500;
      color: #fff;
    `;

    // 关闭按钮
    const closeFullscreenButton = document.createElement("div");
    closeFullscreenButton.innerHTML = `&times;`;
    closeFullscreenButton.style.cssText = `
      font-size: 30px;
      color: #fff;
      cursor: pointer;
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      transition: all 0.2s ease;
    `;

    closeFullscreenButton.addEventListener("mouseover", () => {
      closeFullscreenButton.style.backgroundColor = "rgba(255, 255, 255, 0.1)";
    });

    closeFullscreenButton.addEventListener("mouseout", () => {
      closeFullscreenButton.style.backgroundColor = "transparent";
    });

    closeFullscreenButton.addEventListener("click", () => {
      document.body.removeChild(fullscreenOverlay);
    });

    fullscreenHeader.appendChild(fullscreenTitle);
    fullscreenHeader.appendChild(closeFullscreenButton);

    // 创建全屏代码预览
    const fullscreenCodeContainer = document.createElement("div");
    fullscreenCodeContainer.style.cssText = `
      flex: 1;
      overflow: auto;
      background-color: rgba(30, 30, 30, 0.9);
      border-radius: 6px;
      border: 1px solid rgba(255, 255, 255, 0.1);
    `;

    const fullscreenCodePre = document.createElement("pre");
    fullscreenCodePre.style.cssText = `
      margin: 0;
      padding: 20px;
      font-family: 'Consolas', 'Monaco', monospace;
      font-size: 14px;
      line-height: 1.5;
    `;

    const fullscreenCode = document.createElement("code");
    fullscreenCode.className = "language-javascript";

    // 如果已经有代码内容，直接显示
    if (packageData.code) {
      fullscreenCode.textContent = packageData.code;
    } else {
      fullscreenCode.textContent = "加载中...";
      // 尝试获取代码内容
      fetchCodeContent(packageData.codeUrl)
        .then((content) => {
          packageData.code = content;
          fullscreenCode.textContent = content;

          // 应用高亮
          setTimeout(() => {
            hljs.highlightAll();
          }, 10);
        })
        .catch((error) => {
          console.error("获取代码内容失败:", error);
          fullscreenCode.textContent = "加载代码失败: " + error.message;
        });
    }

    fullscreenCodePre.appendChild(fullscreenCode);
    fullscreenCodeContainer.appendChild(fullscreenCodePre);

    fullscreenOverlay.appendChild(fullscreenHeader);
    fullscreenOverlay.appendChild(fullscreenCodeContainer);

    document.body.appendChild(fullscreenOverlay);

    // 应用高亮
    setTimeout(() => {
      hljs.highlightAll();
    }, 10);
  });

  // Update the part where codeSnippetLink is appended to include the fullscreen button:

  codePreviewTitle.appendChild(codeSnippetLink);
  codePreviewTitle.appendChild(fullscreenButton);

  // 代码预览区域的折叠/展开功能
  let isCodeCollapsed = false;
  codeSnippetLink.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();

    const codeLines = packageData.code.split("\n");
    isCodeCollapsed = !isCodeCollapsed;

    if (isCodeCollapsed) {
      // 切换到折叠状态
      const previewLines =
        codeLines.slice(0, 15).join("\n") +
        (codeLines.length > 15 ? "\n// ...(省略剩余代码)" : "");

      // 为简短代码创建高亮
      const codeContainer = document.createElement("code");
      codeContainer.className = "language-javascript";
      codeContainer.textContent = previewLines;

      // 清空pre内容并添加新的代码元素
      codePreview.innerHTML = "";
      codePreview.appendChild(codeContainer);

      // 应用代码高亮
      hljs.highlightAll();

      codeSnippetLink.textContent = "展开完整代码";
      codePreview.style.maxHeight = "200px";
    } else {
      // 切换到展开状态
      // 为完整代码创建高亮
      const codeContainer = document.createElement("code");
      codeContainer.className = "language-javascript";
      codeContainer.textContent = packageData.code;

      // 清空pre内容并添加新的代码元素
      codePreview.innerHTML = "";
      codePreview.appendChild(codeContainer);

      // 应用代码高亮
      hljs.highlightAll();

      codeSnippetLink.textContent = "折叠代码";
      codePreview.style.maxHeight = "400px";
    }
  });

  codePreviewSection.appendChild(codePreviewTitle);

  // 创建代码预览元素
  const codePreview = document.createElement("pre");
  codePreview.style.cssText = `
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 13px;
    line-height: 1.4;
    background-color: rgba(30, 30, 30, 0.9);
    padding: 12px;
    border-radius: 6px;
    border: 1px solid rgba(255, 255, 255, 0.05);
    color: #e0e0e0;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: auto;
    max-height: 400px;
    margin: 0;
  `;

  // 使用highlight.js添加语法高亮
  const codeContainer = document.createElement("code");
  codeContainer.className = "language-javascript";

  // 检查是否已有代码内容，否则显示加载提示并从URL获取
  if (!packageData.code && packageData.codeUrl) {
    codeContainer.textContent = "正在加载代码内容...";

    // 异步获取代码内容
    fetchCodeContent(packageData.codeUrl)
      .then((content) => {
        // 存储代码内容
        packageData.code = content;
        // 更新显示
        codeContainer.textContent = content;

        hljs.highlightAll();
      })
      .catch((error) => {
        console.error("获取代码内容失败:", error);
        codeContainer.textContent = "加载代码失败: " + error.message;
      });
  } else {
    codeContainer.textContent = packageData.code || "暂无代码内容";
  }

  codePreview.appendChild(codeContainer);

  // 添加代码预览到区域
  codePreviewSection.appendChild(codePreview);
  scrollableContent.appendChild(codePreviewSection);

  // 如果highlight.js可用，应用高亮
  setTimeout(() => {
    hljs.highlightAll();
  }, 10);

  // 固定在底部的按钮区域
  const buttonsArea = document.createElement("div");
  buttonsArea.className = "code-package-confirm-buttons";
  buttonsArea.style.cssText = `
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    padding-top: 15px;
    position: sticky;
    background-color: rgba(35, 35, 35, 0.95);
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    margin: 0 -30px -30px -30px;
    padding: 20px 30px;
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.2);
    z-index: 1;
  `;

  // 取消按钮
  const cancelBtn = document.createElement("button");
  cancelBtn.textContent = "取消";
  cancelBtn.className = "cancel";
  cancelBtn.style.cssText = `
    background-color: rgba(50, 50, 50, 0.8);
    color: #ccc;
    border: 1px solid rgba(150, 150, 150, 0.3);
    border-radius: 8px;
    padding: 10px 20px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    min-width: 100px;
  `;

  cancelBtn.addEventListener("mouseover", () => {
    cancelBtn.style.backgroundColor = "rgba(60, 60, 60, 0.9)";
  });

  cancelBtn.addEventListener("mouseout", () => {
    cancelBtn.style.backgroundColor = "rgba(50, 50, 50, 0.8)";
  });

  // 确认按钮
  const confirmBtn = document.createElement("button");
  confirmBtn.textContent =
    packageData.importType === "console"
      ? "我已了解风险，确认导入"
      : "确认导入";
  confirmBtn.className = "confirm";
  confirmBtn.style.cssText = `
    background-color: ${
      packageData.importType === "console"
        ? "rgba(255, 60, 60, 0.8)"
        : "rgba(77, 138, 240, 0.8)"
    };
    color: #ffffff;
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px ${
      packageData.importType === "console"
        ? "rgba(255, 60, 60, 0.4)"
        : "rgba(77, 138, 240, 0.4)"
    };
    min-width: 150px;
  `;

  confirmBtn.addEventListener("mouseover", () => {
    confirmBtn.style.backgroundColor =
      packageData.importType === "console"
        ? "rgba(255, 60, 60, 0.9)"
        : "rgba(77, 138, 240, 0.9)";
    confirmBtn.style.transform = "translateY(-2px)";
    confirmBtn.style.boxShadow = `0 4px 12px ${
      packageData.importType === "console"
        ? "rgba(255, 60, 60, 0.5)"
        : "rgba(77, 138, 240, 0.5)"
    }`;
  });

  confirmBtn.addEventListener("mouseout", () => {
    confirmBtn.style.backgroundColor =
      packageData.importType === "console"
        ? "rgba(255, 60, 60, 0.8)"
        : "rgba(77, 138, 240, 0.8)";
    confirmBtn.style.transform = "translateY(0)";
    confirmBtn.style.boxShadow = `0 2px 8px ${
      packageData.importType === "console"
        ? "rgba(255, 60, 60, 0.4)"
        : "rgba(77, 138, 240, 0.4)"
    }`;
  });

  // 添加按钮事件
  cancelBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    document.body.removeChild(modalOverlay);
  });

  confirmBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    // 获取选中的导入选项
    let importType = packageData.importType;

    // 如果是控制台导入，查看用户是否选择了其他选项
    if (importType === "console") {
      const selectedOption = modalOverlay.querySelector(
        'input[name="import-option"]:checked'
      );
      if (selectedOption) {
        importType = selectedOption.value;
      }
    }

    // 存储一份数据的副本，以防止引用问题
    const packageDataCopy = JSON.parse(JSON.stringify(packageData));

    // 调用导入函数
    importCodePackage(packageDataCopy, importType);

    // 移除确认区域
    document.body.removeChild(modalOverlay);
  });

  buttonsArea.appendChild(cancelBtn);
  buttonsArea.appendChild(confirmBtn);
  confirmArea.appendChild(buttonsArea);

  // 将确认区域添加到模态背景
  modalOverlay.appendChild(confirmArea);

  // 添加ESC键关闭功能
  const handleKeyDown = (e) => {
    if (e.key === "Escape") {
      document.body.removeChild(modalOverlay);
      window.removeEventListener("keydown", handleKeyDown);
    }
  };
  window.addEventListener("keydown", handleKeyDown);

  // 添加到body
  document.body.appendChild(modalOverlay);
}

/**
 * 创建导入选项
 * @param {string} id - 选项ID
 * @param {string} title - 选项标题
 * @param {string} description - 选项描述
 * @param {boolean} isChecked - 是否默认选中
 * @returns {HTMLElement} 创建的选项元素
 */
function createImportOption(id, title, description, isChecked) {
  const optionContainer = document.createElement("div");
  optionContainer.style.cssText = `
    display: flex;
    align-items: flex-start;
  `;

  // 创建单选按钮
  const radio = document.createElement("input");
  radio.type = "radio";
  radio.id = id;
  radio.name = "import-option";
  radio.value = id;
  radio.checked = isChecked;
  radio.style.cssText = `
    margin-right: 10px;
    margin-top: 3px;
  `;

  // 创建标签
  const label = document.createElement("label");
  label.htmlFor = id;
  label.style.cssText = `
    display: flex;
    flex-direction: column;
    cursor: pointer;
  `;

  const titleSpan = document.createElement("span");
  titleSpan.textContent = title;
  titleSpan.style.cssText = `
    font-weight: 500;
    color: #fff;
    margin-bottom: 4px;
  `;

  const descSpan = document.createElement("span");
  descSpan.textContent = description;
  descSpan.style.cssText = `
    font-size: 12px;
    color: #aaa;
  `;

  label.appendChild(titleSpan);
  label.appendChild(descSpan);

  optionContainer.appendChild(radio);
  optionContainer.appendChild(label);

  return optionContainer;
}

/**
 * 导入代码包
 * @param {Object} packageData - 代码包数据
 * @param {string} importType - 导入类型
 */
async function importCodePackage(packageData, importType) {
  try {
    // 显示加载通知
    showNotification(`正在加载代码包: ${packageData.title}...`, "info");

    // 获取代码包内容
    let codeContent;
    try {
      codeContent = await fetchCodeContent(packageData.codeUrl);
    } catch (error) {
      console.error("获取代码内容失败:", error);
      showNotification(
        "获取代码内容失败: " + (error.message || "未知错误"),
        "error"
      );
      return;
    }

    // 存储代码内容到packageData对象中
    packageData.code = codeContent;

    if (importType === "console-import" || importType === "console") {
      // 控制台导入
      try {
        // 查找控制台并插入代码
        const consoleEditor = document.querySelector(".monaco-editor");
        if (!consoleEditor) {
          showNotification("导入失败: 未找到编辑器", "error");
          return;
        }

        if (!unsafeWindow.box3EditCore) {
          showNotification("导入失败: 编辑器API不可用", "error");
          return;
        }

        // 使用脚本执行API直接执行代码
        if (
          unsafeWindow.box3EditCore.debugger &&
          unsafeWindow.box3EditCore.debugger.scriptEval
        ) {
          // 执行代码
          unsafeWindow.box3EditCore.debugger.scriptEval(packageData.code);

          // 通知用户
          showNotification(
            `已成功导入并执行代码包: ${packageData.title}`,
            "success"
          );
        } else {
          // 回退到编辑器
          const editor = unsafeWindow.editObk;
          if (!editor) {
            showNotification("导入失败: 编辑器实例不可用", "error");
            return;
          }

          const model = editor.getModel();
          if (!model) {
            showNotification("导入失败: 编辑器模型不可用", "error");
            return;
          }

          model.setValue(packageData.code);
          // 通知用户
          showNotification(
            `已导入代码包到编辑器: ${packageData.title}`,
            "success"
          );
        }
      } catch (error) {
        console.error("控制台导入失败:", error);
        showNotification("导入失败: " + (error.message || "未知错误"), "error");
      }
    } else if (importType === "script-import") {
      // 新脚本导入
      try {
        // 尝试创建新脚本
        if (
          !unsafeWindow.box3EditCore ||
          !unsafeWindow.box3EditCore.codeEditorController
        ) {
          showNotification("创建脚本失败: 编辑器API不可用", "error");
          return;
        }

        importAsNewScript(packageData);
      } catch (error) {
        console.error("创建新脚本失败:", error);
        showNotification(
          "创建脚本失败: " + (error.message || "未知错误"),
          "error"
        );
      }
    } else if (importType === "server") {
      // 服务端导入
      try {
        if (
          !unsafeWindow.box3EditCore ||
          !unsafeWindow.box3EditCore.codeEditorController
        ) {
          showNotification("服务端导入失败: 编辑器API不可用", "error");
          return;
        }

        // 服务端导入，不传参数或传false
        unsafeWindow.box3EditCore.codeEditorController.addFile();

        setTimeout(() => {
          // 导入代码到新创建的文件
          importToNewlyCreatedFile(packageData);
        }, 100);
      } catch (error) {
        console.error("服务端导入失败:", error);
        showNotification(
          "服务端导入失败: " + (error.message || "未知错误"),
          "error"
        );
      }
    } else if (importType === "client") {
      // 客户端导入
      try {
        if (
          !unsafeWindow.box3EditCore ||
          !unsafeWindow.box3EditCore.codeEditorController
        ) {
          showNotification("客户端导入失败: 编辑器API不可用", "error");
          return;
        }

        // 客户端导入，传true参数
        unsafeWindow.box3EditCore.codeEditorController.addFile(true);

        setTimeout(() => {
          // 导入代码到新创建的文件
          importToNewlyCreatedFile(packageData);
        }, 100);
      } catch (error) {
        console.error("客户端导入失败:", error);
        showNotification(
          "客户端导入失败: " + (error.message || "未知错误"),
          "error"
        );
      }
    }
  } catch (error) {
    console.error("导入代码包主函数出错:", error);
    showNotification(`导入失败: ${error.message || "未知错误"}`, "error");
  }
}

/**
 * 创建新脚本并导入代码
 * @param {Object} packageData - 代码包数据
 */
function importAsNewScript(packageData) {
  try {
    // 确保API可用
    if (
      !unsafeWindow.box3EditCore ||
      !unsafeWindow.box3EditCore.codeEditorController
    ) {
      showNotification("创建失败: 编辑器API不可用", "error");
      return;
    }

    unsafeWindow.box3EditCore.codeEditorController.addFile(
      packageData.isClient
    );

    setTimeout(() => {
      // 导入代码到新创建的文件
      importToNewlyCreatedFile(packageData);
    }, 100);
  } catch (error) {
    console.error("创建新脚本过程中出错:", error);
    showNotification(`创建脚本失败: ${error.message || "未知错误"}`, "error");
  }
}

/**
 * 导入代码到新创建的文件
 * @param {Object} packageData - 代码包数据
 */
function importToNewlyCreatedFile(packageData) {
  try {
    if (
      !unsafeWindow.box3EditCore.frameState ||
      !unsafeWindow.box3EditCore.frameState.codeEditor ||
      !unsafeWindow.box3EditCore.frameState.codeEditor.fileDict
    ) {
      showNotification("导入失败: 文件列表不可用", "error");
      return;
    }

    // 获取文件列表
    const fileDict = unsafeWindow.box3EditCore.frameState.codeEditor.fileDict;

    // 获取最新创建的脚本文件
    const files = Object.entries(fileDict)
      .map(([key, value]) => ({ key, value }))
      .sort((a, b) => a.value.order - b.value.order);

    // 获取最新的文件
    const idx = files[Object.keys(fileDict).length - 1];

    if (!idx) {
      showNotification("导入失败: 无法获取新创建的文件", "error");
      return;
    }

    unsafeWindow.box3EditCore.frameState.codeEditor.selectedFileId = idx.key;

    // 生成文件名
    let fileName = packageData.type
      .toLowerCase()
      .replace(/\s+/g, "-")
      .replace(/[^a-zA-Z0-9\-_]/g, "");

    // 确保文件名以.js结尾
    if (!fileName.endsWith(".js")) {
      fileName += ".js";
    }

    setTimeout(() => {
      const editObk = unsafeWindow.editObk;

      if (editObk && editObk.getModel()) {
        editObk.getModel().setValue(packageData.code);

        // 通知用户
        showNotification(`已成功导入代码包: ${packageData.title}`);
      } else {
        console.error("无法获取编辑器模型");
        showNotification("导入失败: 无法获取编辑器模型", "error");
      }

      setTimeout(() => {
        unsafeWindow.box3EditCore.codeEditorController.renameFile(
          idx.key,
          fileName
        );
      }, 100);
    }, 100);
  } catch (error) {
    console.error("导入代码到新文件时出错:", error);
    showNotification(`导入失败: ${error.message || "未知错误"}`, "error");
  }
}

/**
 * 显示通知消息
 * @param {string} message - 通知消息
 * @param {string} type - 通知类型：'success', 'error', 'info'
 */
function showNotification(message, type = "success") {
  const notification = document.createElement("div");
  notification.className = `code-package-notification ${type}`;
  notification.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 12px 20px;
    background-color: ${
      type === "error" ? "rgba(255, 76, 76, 0.95)" : "rgba(77, 138, 240, 0.95)"
    };
    color: white;
    border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    font-size: 14px;
    z-index: 99999;
    animation: slideInNotification 0.3s ease-out forwards;
  `;

  notification.textContent = message;
  document.body.appendChild(notification);

  // 添加动画样式
  const style = document.createElement("style");
  style.textContent = `
    @keyframes slideInNotification {
      from {
        transform: translateX(100%);
        opacity: 0;
      }
      to {
        transform: translateX(0);
        opacity: 1;
      }
    }
    
    @keyframes fadeOutNotification {
      from {
        transform: translateX(0);
        opacity: 1;
      }
      to {
        transform: translateX(100%);
        opacity: 0;
      }
    }
  `;
  document.head.appendChild(style);

  // 3秒后移除通知
  setTimeout(() => {
    notification.style.animation = "fadeOutNotification 0.3s ease-in forwards";
    setTimeout(() => {
      if (document.body.contains(notification)) {
        document.body.removeChild(notification);
      }
    }, 300);
  }, 3000);
}

/**
 * 从URL获取代码内容
 * @param {string} url - 代码包URL
 * @returns {Promise<string>} 代码内容
 */
async function fetchCodeContent(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`获取代码失败: ${response.status}`);
    }

    // 获取原始文本
    let code = await response.text();

    // 如果包含 UserScript 标记，则删除该部分和 gameConfig 对象
    if (code.includes("// ==UserScript==")) {
      // 查找 gameConfig 对象结束位置
      const configStart = code.indexOf("const gameConfig =");
      if (configStart !== -1) {
        let braceCount = 0;
        let i = code.indexOf("{", configStart);
        let endPos = i;

        if (i !== -1) {
          braceCount = 1;
          i++;

          // 找到匹配的闭合大括号
          while (i < code.length && braceCount > 0) {
            if (code[i] === "{") braceCount++;
            else if (code[i] === "}") braceCount--;

            if (braceCount === 0) {
              endPos = i;
              break;
            }
            i++;
          }

          // 找到配置对象结束后的"// ==UserScript=="标记
          const endMarker = code.indexOf("// ==UserScript==", endPos);
          if (endMarker !== -1) {
            const scriptEnd = code.indexOf("\n", endMarker);
            if (scriptEnd !== -1) {
              // 删除从开始到标记结束的内容
              code = code.substring(scriptEnd + 1).trim();
            }
          }
        }
      }
    }

    return code;
  } catch (error) {
    console.error("获取代码内容出错:", error);
    throw error;
  }
}

/**
 * 显示投稿模态框
 */
function showSubmitModal() {
  // 创建全屏遮罩
  const modalOverlay = document.createElement("div");
  modalOverlay.className = "submit-modal-overlay";
  modalOverlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(5px);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 12000;
    animation: fadeIn 0.2s ease;
  `;

  // 创建投稿模态框
  const submitModal = document.createElement("div");
  submitModal.className = "submit-modal";
  submitModal.style.cssText = `
    width: 90%;
    max-width: 600px;
    background-color: rgba(35, 35, 35, 0.95);
    border-radius: 16px;
    padding: 30px;
    display: flex;
    flex-direction: column;
    position: relative;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(99, 230, 190, 0.3);
    max-height: 80vh;
    overflow: hidden;
  `;

  // 添加头部装饰条
  const headerDecoration = document.createElement("div");
  headerDecoration.style.cssText = `
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #63e6be, #4d8af0);
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    z-index: 2;
  `;
  submitModal.appendChild(headerDecoration);

  // 创建内容滚动区域
  const scrollableContent = document.createElement("div");
  scrollableContent.style.cssText = `
    flex: 1;
    overflow-y: auto;
    padding-right: 10px;
    margin-right: -10px;
    margin-bottom: 20px;
  `;
  submitModal.appendChild(scrollableContent);

  // 创建标题
  const submitTitle = document.createElement("h2");
  submitTitle.textContent = "代码包投稿/更新";
  submitTitle.style.cssText = `
    font-size: 22px;
    font-weight: 500;
    color: #fff;
    margin: 0 0 20px 0;
    padding-bottom: 15px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  `;
  scrollableContent.appendChild(submitTitle);

  // 创建投稿表单
  const submitForm = document.createElement("div");
  submitForm.style.cssText = `
    display: flex;
    flex-direction: column;
    gap: 20px;
  `;

  // 创建代码包信息区域
  const packageInfo = document.createElement("div");
  packageInfo.style.cssText = `
    display: flex;
    flex-direction: column;
    gap: 15px;
  `;

  // 代码包标题输入
  const titleInput = createFormField(
    "代码包标题",
    "text",
    "请输入代码包标题",
    true
  );
  packageInfo.appendChild(titleInput);

  const idInput = createFormField(
    "代码包标识",
    "text",
    "请输入代码包标识（纯英文）",
    true
  );
  packageInfo.appendChild(idInput);

  // 代码包类型选择
  const typeField = createFormField("代码包类型", "select", "", true);
  const typeSelect = typeField.querySelector("select");

  // 添加选项
  const typeOptions = [
    { value: false, label: "服务端" },
    { value: true, label: "客户端" },
  ];

  typeOptions.forEach((option) => {
    const optElement = document.createElement("option");
    optElement.value = option.value;
    optElement.textContent = option.label;
    typeSelect.appendChild(optElement);
  });

  // 代码包类型选择
  const consoleField = createFormField(
    "是否支持导入控制台一键执行？",
    "select",
    "",
    true
  );
  const consoleSelect = consoleField.querySelector("select");

  // 添加选项
  const consoleOptions = [
    { value: false, label: "否" },
    { value: true, label: "是" },
  ];

  consoleOptions.forEach((option) => {
    const optElement = document.createElement("option");
    optElement.value = option.value;
    optElement.textContent = option.label;
    consoleSelect.appendChild(optElement);
  });

  packageInfo.appendChild(typeField);
  packageInfo.appendChild(consoleField);
  // 代码包描述输入
  const descField = createFormField(
    "代码包描述",
    "textarea",
    "请输入代码包描述，建议详细说明代码包的用途、功能、使用方法等",
    true
  );
  const descInput = descField.querySelector("textarea");
  descInput.rows = 5;
  packageInfo.appendChild(descField);

  // 文档URL输入
  const docUrlInput = createFormField("文档URL", "text", "填写文档URL（可选）");
  packageInfo.appendChild(docUrlInput);

  // 文件上传区域
  const fileUploadField = document.createElement("div");
  fileUploadField.style.cssText = `
    margin-top: 5px;
  `;

  const fileUploadLabel = document.createElement("div");
  fileUploadLabel.style.cssText = `
    font-size: 14px;
    font-weight: 500;
    color: #ddd;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
  `;

  // 添加标签文本
  fileUploadLabel.textContent = "上传代码文件";

  // 添加红色星号
  const fileRequiredMark = document.createElement("span");
  fileRequiredMark.textContent = "*";
  fileRequiredMark.style.cssText = `
    color: #ff3c3c;
    margin-left: 4px;
    font-size: 16px;
  `;
  fileUploadLabel.appendChild(fileRequiredMark);

  fileUploadField.appendChild(fileUploadLabel);

  // 创建文件上传区域
  const fileDropArea = document.createElement("div");
  fileDropArea.style.cssText = `
    border: 2px dashed rgba(99, 230, 190, 0.3);
    border-radius: 8px;
    padding: 30px 20px;
    text-align: center;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: rgba(99, 230, 190, 0.05);
  `;

  const fileIcon = document.createElement("div");
  fileIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="rgba(99, 230, 190, 0.6)" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg>`;
  fileIcon.style.cssText = `
    margin-bottom: 10px;
    display: flex;
    justify-content: center;
  `;
  fileDropArea.appendChild(fileIcon);

  const fileText = document.createElement("div");
  fileText.innerHTML = `<span style="color: #63e6be;">点击选择文件</span> 或拖拽文件到此处`;
  fileText.style.cssText = `
    color: #ddd;
    font-size: 14px;
    margin-bottom: 5px;
  `;
  fileDropArea.appendChild(fileText);

  const fileHint = document.createElement("div");
  fileHint.textContent = "支持 .js 格式文件";
  fileHint.style.cssText = `
    color: #999;
    font-size: 12px;
  `;
  fileDropArea.appendChild(fileHint);

  // 创建实际的文件输入框（隐藏）
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.accept = ".js";
  fileInput.style.cssText = `
    display: none;
  `;
  fileDropArea.appendChild(fileInput);

  // 文件上传状态显示
  const fileStatus = document.createElement("div");
  fileStatus.style.cssText = `
    display: none;
    margin-top: 10px;
    padding: 10px;
    border-radius: 6px;
    font-size: 13px;
    background-color: rgba(77, 138, 240, 0.1);
    border: 1px solid rgba(77, 138, 240, 0.2);
    color: #ddd;
  `;

  // 点击和拖拽处理
  fileDropArea.addEventListener("click", () => {
    fileInput.click();
  });

  fileDropArea.addEventListener("dragover", (e) => {
    e.preventDefault();
    fileDropArea.style.backgroundColor = "rgba(99, 230, 190, 0.1)";
    fileDropArea.style.borderColor = "rgba(99, 230, 190, 0.5)";
  });

  fileDropArea.addEventListener("dragleave", () => {
    fileDropArea.style.backgroundColor = "rgba(99, 230, 190, 0.05)";
    fileDropArea.style.borderColor = "rgba(99, 230, 190, 0.3)";
  });

  fileDropArea.addEventListener("drop", (e) => {
    e.preventDefault();
    fileDropArea.style.backgroundColor = "rgba(99, 230, 190, 0.05)";
    fileDropArea.style.borderColor = "rgba(99, 230, 190, 0.3)";

    if (e.dataTransfer.files.length) {
      fileInput.files = e.dataTransfer.files;
      updateFileStatus(fileInput.files[0], fileStatus);
    }
  });

  fileInput.addEventListener("change", () => {
    if (fileInput.files.length) {
      updateFileStatus(fileInput.files[0], fileStatus);
    }
  });

  fileUploadField.appendChild(fileDropArea);
  fileUploadField.appendChild(fileStatus);

  packageInfo.appendChild(fileUploadField);

  submitForm.appendChild(packageInfo);
  scrollableContent.appendChild(submitForm);

  // 固定在底部的按钮区域
  const buttonsArea = document.createElement("div");
  buttonsArea.style.cssText = `
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    padding-top: 15px;
    position: sticky;
    background-color: rgba(35, 35, 35, 0.95);
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    margin: 0 -30px -30px -30px;
    padding: 20px 30px;
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.2);
    z-index: 1;
  `;

  // 取消按钮
  const cancelBtn = document.createElement("button");
  cancelBtn.textContent = "取消";
  cancelBtn.className = "cancel";
  cancelBtn.style.cssText = `
    background-color: rgba(50, 50, 50, 0.8);
    color: #ccc;
    border: 1px solid rgba(150, 150, 150, 0.3);
    border-radius: 8px;
    padding: 10px 20px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    min-width: 100px;
  `;

  cancelBtn.addEventListener("mouseover", () => {
    cancelBtn.style.backgroundColor = "rgba(60, 60, 60, 0.9)";
  });

  cancelBtn.addEventListener("mouseout", () => {
    cancelBtn.style.backgroundColor = "rgba(50, 50, 50, 0.8)";
  });

  // 确认按钮
  const submitBtn = document.createElement("button");
  submitBtn.textContent = "确认投稿";
  submitBtn.className = "submit";
  submitBtn.style.cssText = `
    background-color: rgba(99, 230, 190, 0.8);
    color: #ffffff;
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(99, 230, 190, 0.4);
    min-width: 150px;
  `;

  submitBtn.addEventListener("mouseover", () => {
    submitBtn.style.backgroundColor = "rgba(99, 230, 190, 0.9)";
    submitBtn.style.transform = "translateY(-2px)";
    submitBtn.style.boxShadow = "0 4px 12px rgba(99, 230, 190, 0.5)";
  });

  submitBtn.addEventListener("mouseout", () => {
    submitBtn.style.backgroundColor = "rgba(99, 230, 190, 0.8)";
    submitBtn.style.transform = "translateY(0)";
    submitBtn.style.boxShadow = "0 2px 8px rgba(99, 230, 190, 0.4)";
  });

  // 添加按钮事件
  cancelBtn.addEventListener("click", () => {
    document.body.removeChild(modalOverlay);
  });

  submitBtn.addEventListener("click", () => {
    handleSubmit(
      {
        id: idInput.querySelector("input").value,
        title: titleInput.querySelector("input").value,
        isClient: typeSelect.value,
        description: descInput.value,
        docUrl: docUrlInput.querySelector("input").value,
        file: fileInput.files[0],
        isConsole: consoleSelect.value,
      },
      modalOverlay
    );
  });

  buttonsArea.appendChild(cancelBtn);
  buttonsArea.appendChild(submitBtn);
  submitModal.appendChild(buttonsArea);

  // 将模态框添加到页面
  modalOverlay.appendChild(submitModal);
  document.body.appendChild(modalOverlay);

  // 添加ESC键关闭功能
  const handleKeyDown = (e) => {
    if (e.key === "Escape") {
      document.body.removeChild(modalOverlay);
      window.removeEventListener("keydown", handleKeyDown);
    }
  };
  window.addEventListener("keydown", handleKeyDown);
}

/**
 * 创建表单字段
 * @param {string} label - 字段标签
 * @param {string} type - 字段类型
 * @param {string} placeholder - 占位文本
 * @param {boolean} required - 是否必填
 * @returns {HTMLElement} 表单字段元素
 */
function createFormField(label, type, placeholder, required = false) {
  const fieldContainer = document.createElement("div");
  fieldContainer.style.cssText = `
    display: flex;
    flex-direction: column;
  `;

  const fieldLabel = document.createElement("label");
  fieldLabel.style.cssText = `
    font-size: 14px;
    font-weight: 500;
    color: #ddd;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
  `;

  // 添加标签文本
  const labelText = document.createTextNode(label);
  fieldLabel.appendChild(labelText);

  // 如果字段是必填的，添加红色星号
  if (required) {
    const requiredMark = document.createElement("span");
    requiredMark.textContent = "*";
    requiredMark.style.cssText = `
      color: #ff3c3c;
      margin-left: 4px;
      font-size: 16px;
    `;
    fieldLabel.appendChild(requiredMark);
  }

  fieldContainer.appendChild(fieldLabel);

  if (type === "textarea") {
    const textarea = document.createElement("textarea");
    textarea.placeholder = placeholder;
    textarea.style.cssText = `
      background-color: rgba(30, 30, 30, 0.8);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 6px;
      padding: 10px 12px;
      color: #fff;
      font-size: 14px;
      resize: vertical;
      min-height: 80px;
      font-family: inherit;
    `;

    textarea.addEventListener("focus", () => {
      textarea.style.borderColor = "rgba(99, 230, 190, 0.5)";
      textarea.style.boxShadow = "0 0 0 2px rgba(99, 230, 190, 0.15)";
    });

    textarea.addEventListener("blur", () => {
      textarea.style.borderColor = "rgba(255, 255, 255, 0.1)";
      textarea.style.boxShadow = "none";
    });

    fieldContainer.appendChild(textarea);
  } else if (type === "select") {
    const select = document.createElement("select");
    select.style.cssText = `
      background-color: rgba(30, 30, 30, 0.8);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 6px;
      padding: 10px 12px;
      color: #fff;
      font-size: 14px;
      appearance: none;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: right 10px center;
      background-size: 16px;
      padding-right: 30px;
    `;

    select.addEventListener("focus", () => {
      select.style.borderColor = "rgba(99, 230, 190, 0.5)";
      select.style.boxShadow = "0 0 0 2px rgba(99, 230, 190, 0.15)";
    });

    select.addEventListener("blur", () => {
      select.style.borderColor = "rgba(255, 255, 255, 0.1)";
      select.style.boxShadow = "none";
    });

    fieldContainer.appendChild(select);
  } else {
    const input = document.createElement("input");
    input.type = type;
    input.placeholder = placeholder;
    input.style.cssText = `
      background-color: rgba(30, 30, 30, 0.8);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 6px;
      padding: 10px 12px;
      color: #fff;
      font-size: 14px;
    `;

    input.addEventListener("focus", () => {
      input.style.borderColor = "rgba(99, 230, 190, 0.5)";
      input.style.boxShadow = "0 0 0 2px rgba(99, 230, 190, 0.15)";
    });

    input.addEventListener("blur", () => {
      input.style.borderColor = "rgba(255, 255, 255, 0.1)";
      input.style.boxShadow = "none";
    });

    fieldContainer.appendChild(input);
  }

  return fieldContainer;
}

/**
 * 更新文件状态显示
 * @param {File} file - 上传的文件
 * @param {HTMLElement} statusElement - 状态显示元素
 */
function updateFileStatus(file, statusElement) {
  if (!file) return;

  // 检查文件类型
  if (!file.name.endsWith(".js")) {
    statusElement.style.display = "block";
    statusElement.textContent = "❌ 请上传.js格式的JavaScript文件";
    statusElement.style.backgroundColor = "rgba(255, 76, 76, 0.1)";
    statusElement.style.borderColor = "rgba(255, 76, 76, 0.3)";
    return;
  }

  // 显示文件信息
  statusElement.style.display = "block";
  statusElement.innerHTML = `
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <span>✅ 已选择: ${file.name}</span>
      <span style="color: #999; font-size: 12px;">${formatFileSize(
        file.size
      )}</span>
    </div>
  `;
  statusElement.style.backgroundColor = "rgba(99, 230, 190, 0.1)";
  statusElement.style.borderColor = "rgba(99, 230, 190, 0.3)";
}

/**
 * 格式化文件大小
 * @param {number} bytes - 文件大小（字节）
 * @returns {string} 格式化后的大小
 */
function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + " B";
  else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB";
  else return (bytes / 1048576).toFixed(1) + " MB";
}

/**
 * 处理表单提交
 * @param {Object} formData - 表单数据
 * @param {HTMLElement} modalOverlay - 模态框遮罩元素
 */
function handleSubmit(formData, modalOverlay) {
  // 简单的表单验证
  if (!formData.title.trim()) {
    showNotification("请输入代码包标题", "error");
    return;
  }
  if (!formData.id.trim()) {
    showNotification("请输入代码包标识", "error");
    return;
  }

  if (!formData.description.trim()) {
    showNotification("请输入代码包描述", "error");
    return;
  }

  if (!formData.file) {
    showNotification("请上传代码文件", "error");
    return;
  }

  // 显示加载状态
  const loadingNotification = document.createElement("div");
  loadingNotification.className = "loading-notification";
  loadingNotification.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100000;
  `;

  const loadingContent = document.createElement("div");
  loadingContent.style.cssText = `
    background-color: rgba(40, 40, 40, 0.9);
    padding: 20px 30px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  `;

  const loadingSpinner = document.createElement("div");
  loadingSpinner.style.cssText = `
    width: 24px;
    height: 24px;
    border: 3px solid rgba(77, 138, 240, 0.3);
    border-radius: 50%;
    border-top-color: rgba(77, 138, 240, 1);
    animation: spin 1s linear infinite;
    margin-right: 15px;
  `;

  const loadingText = document.createElement("div");
  loadingText.textContent = "上传处理中...";
  loadingText.style.cssText = `
    color: #fff;
    font-size: 16px;
  `;

  loadingContent.appendChild(loadingSpinner);
  loadingContent.appendChild(loadingText);
  loadingNotification.appendChild(loadingContent);

  // 添加动画样式
  const styleElement = document.createElement("style");
  styleElement.textContent = `
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
  `;
  document.head.appendChild(styleElement);

  document.body.appendChild(loadingNotification);

  // 获取用户ID
  let userId = null;

  // 从授权令牌中获取用户ID或从API获取用户信息
  const getUserId = async () => {
    try {
      // 获取授权令牌
      const authorization = unsafeWindow.box3EditCore?.brpc?.headers?.auth;

      if (!authorization) {
        console.warn("未找到授权令牌，将使用匿名投稿");
        return null;
      }

      // 调用API获取用户信息
      const response = await fetch("https://code-api-pc.dao3.fun/auth/user", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: authorization,
        },
      });

      const data = await response.json();

      if (data && data.code === 200 && data.data && data.data.userId) {
        return data.data.userId;
      } else {
        console.warn("获取用户ID失败");
        return null;
      }
    } catch (error) {
      console.error("获取用户ID失败:", error);
      return null;
    }
  };

  // 先获取用户ID，然后继续上传过程
  getUserId()
    .then((id) => {
      userId = id;
      // 上传文件到服务器
      return uploadFile(formData.file);
    })
    .then((fileUrl) => {
      // 创建要发送的数据对象
      const submitData = {
        url: fileUrl,
        title: formData.title,
        type: formData.id,
        doc: formData.description,
        help: formData.docUrl || "",
        isClient: formData.isClient == "true" ? true : false,
        isConsole: formData.isConsole == "true" ? true : false,
      };

      // 如果获取到用户ID，添加到提交数据中
      if (userId) {
        submitData.userId = userId;
      }

      // 发送数据到服务器
      return sendPackageData(submitData);
    })
    .then((result) => {
      // 移除加载状态
      document.body.removeChild(loadingNotification);

      // 显示成功通知
      showNotification(`投稿成功: ${result.msg || "代码包已提交"}`, "success");

      // 关闭模态框
      document.body.removeChild(modalOverlay);

      // 重新加载代码包列表
      refreshCodePackageList();
    })
    .catch((error) => {
      // 移除加载状态
      document.body.removeChild(loadingNotification);

      // 显示错误通知
      showNotification(
        `投稿失败: ${error.message || "上传过程中发生错误"}`,
        "error"
      );
      console.error("投稿失败:", error);
    });
}

/**
 * 上传文件到服务器
 * @param {File} file - 要上传的文件
 * @returns {Promise<string>} 返回上传后的文件URL
 */
async function uploadFile(file) {
  // 创建FormData对象
  const formData = new FormData();
  formData.append("file", file);

  try {
    // 发送POST请求到文件上传API
    const response = await fetch(
      "https://api.box3lab.com/user/up_cat_file?path=box3lab",
      {
        method: "POST",
        body: formData,
      }
    );

    if (!response.ok) {
      throw new Error(`上传失败: ${response.status} ${response.statusText}`);
    }

    // 解析响应获取文件URL
    const result = await response.json();

    if (!result.url) {
      throw new Error("上传成功但未获取到文件URL");
    }

    return result.url;
  } catch (error) {
    console.error("文件上传错误:", error);
    throw error;
  }
}

/**
 * 发送代码包数据到服务器
 * @param {Object} packageData - 代码包数据
 * @returns {Promise<Object>} 服务器响应
 */
async function sendPackageData(packageData) {
  try {
    // 发送POST请求到提交API
    const response = await fetch(
      "https://api.box3lab.com/dao3lab/box/control_up",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
        },
        body: JSON.stringify(packageData),
      }
    );

    if (!response.ok) {
      throw new Error(`提交失败: ${response.status} ${response.statusText}`);
    }

    // 解析响应
    const responseText = await response.text();
    return JSON.parse(responseText);
  } catch (error) {
    console.error("数据提交错误:", error);
    throw error;
  }
}

/**
 * 刷新代码包列表
 */
function refreshCodePackageList() {
  // 查找是否已存在模态框
  const existingModal = document.getElementById("code-package-modal");

  // 如果模态框存在且可见（通过检查opacity）
  if (existingModal && window.getComputedStyle(existingModal).opacity !== "0") {
    // 获取包列表元素
    const packageList = existingModal.querySelector('[style*="column-count"]');

    if (packageList) {
      // 创建并显示加载指示器
      const loadingIndicator = document.createElement("div");
      loadingIndicator.style.cssText = `
        column-span: all;
        text-align: center;
        padding: 30px;
        color: #aaa;
      `;

      const spinner = document.createElement("div");
      spinner.style.cssText = `
        width: 40px;
        height: 40px;
        margin: 0 auto 15px auto;
        border: 3px solid rgba(77, 138, 240, 0.3);
        border-radius: 50%;
        border-top-color: rgb(77, 138, 240);
        animation: spin 1s linear infinite;
      `;

      loadingIndicator.appendChild(spinner);
      loadingIndicator.appendChild(
        document.createTextNode("正在刷新代码包列表...")
      );

      // 清空当前列表并显示加载指示器
      packageList.innerHTML = "";
      packageList.appendChild(loadingIndicator);

      // 重新获取代码包数据
      fetch("https://api.box3lab.com/dao3lab/get_codepackage")
        .then((response) => {
          if (!response.ok) {
            throw new Error(`API响应错误: ${response.status}`);
          }
          return response.json();
        })
        .then((data) => {
          // 处理API返回的数据格式
          const packages = data.map((pkg) => {
            // 确定导入类型
            let importType = pkg.isClient === 1 ? "client" : "server"; // 默认为服务端
            if (pkg.isConsole === 1) {
              importType = "console";
            }

            // 处理type字段，只保留/-/后面的部分
            let cleanType = pkg.type;
            if (pkg.type && pkg.type.includes("/-/")) {
              cleanType = pkg.type.split("/-/")[1];
            }

            return {
              id: pkg.uid,
              title: pkg.title,
              description: pkg.doc || "暂无描述",
              code: "", // 代码内容将在用户选择导入时从URL获取
              codeUrl: pkg.url,
              docUrl: pkg.help,
              importType: importType,
              isClient: pkg.isClient,
              type: cleanType,
              time: pkg.time,
            };
          });

          // 过滤掉没有标题的代码包
          const filteredPackages = packages.filter(
            (pkg) => pkg.title && pkg.title.trim() !== ""
          );

          // 清空包列表
          packageList.innerHTML = "";

          // 创建无结果提示（以防没有包）
          const noResultsMessage = document.createElement("div");
          noResultsMessage.style.cssText = `
            display: none;
            width: 100%;
            text-align: center;
            color: #aaa;
            padding: 40px 20px;
            font-size: 15px;
            column-span: all;
          `;
          noResultsMessage.innerHTML = `
            <div style="margin-bottom: 15px;">
              <svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#aaa" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                <line x1="11" y1="8" x2="11" y2="14"></line>
                <line x1="8" y1="11" x2="14" y2="11"></line>
              </svg>
            </div>
            <div style="font-weight: 500; margin-bottom: 8px;">未找到相关代码包</div>
            <div style="font-size: 13px; opacity: 0.8;">请尝试使用不同的关键词搜索</div>
          `;
          packageList.appendChild(noResultsMessage);

          // 如果没有代码包，显示无结果消息
          if (filteredPackages.length === 0) {
            noResultsMessage.style.display = "block";
            return;
          }

          // 按时间倒序排序，最新的排在前面
          filteredPackages.sort((a, b) => {
            const timeA = a.time ? parseInt(a.time) : 0;
            const timeB = b.time ? parseInt(b.time) : 0;
            return timeB - timeA;
          });

          // 渲染每个代码包
          filteredPackages.forEach((pkg) => {
            // 创建一个随机的最小高度变化，增强瀑布流效果
            const randomHeight = Math.floor(Math.random() * 50) + 150;

            const card = document.createElement("div");
            card.className = "code-package-card";
            card.style.cssText = `
              background-color: rgba(40, 40, 40, 0.7);
              border-radius: 12px;
              overflow: hidden;
              transition: all 0.3s ease;
              border: 1px solid rgba(255, 255, 255, 0.05);
              padding: 0;
              position: relative;
              display: inline-block;
              width: 100%;
              margin-bottom: 20px;
              break-inside: avoid;
              min-height: ${randomHeight}px;
            `;

            // 存储包数据引用以用于搜索
            card.packageData = pkg;

            // 卡片内容
            const cardContent = document.createElement("div");
            cardContent.style.cssText = `
              padding: 20px;
              display: flex;
              flex-direction: column;
              height: 100%;
              box-sizing: border-box;
            `;

            // 标题
            const title = document.createElement("h3");
            title.textContent = pkg.title;
            title.style.cssText = `
              margin: 0;
              font-size: 17px;
              font-weight: 500;
              color: #fff;
              flex: 1;
            `;

            // 显示导入类型标签
            const importTypeLabel = document.createElement("div");
            importTypeLabel.style.cssText = `
              display: inline-block;
              font-size: 11px;
              padding: 3px 8px;
              border-radius: 10px;
              font-weight: 500;
              white-space: nowrap;
              margin-left: 10px;
            `;

            // 根据导入类型设置不同样式
            switch (pkg.importType) {
              case "console":
                importTypeLabel.textContent = "控制台";
                importTypeLabel.style.backgroundColor = "rgb(255 60 60 / 20%)";
                importTypeLabel.style.color = "rgb(255 60 60)";
                importTypeLabel.style.border =
                  "1px solid rgba(255, 60, 60, 0.3)";
                break;
              case "server":
                importTypeLabel.textContent = "服务端";
                importTypeLabel.style.backgroundColor = "rgb(209 83 231 / 20%)";
                importTypeLabel.style.color = "rgb(206 60 231)";
                break;
              case "client":
                importTypeLabel.textContent = "客户端";
                importTypeLabel.style.backgroundColor = "rgb(83 231 199 / 20%)";
                importTypeLabel.style.color = "rgb(83 231 199)";
                break;
            }

            // 创建标题行容器
            const titleRow = document.createElement("div");
            titleRow.style.cssText = `
              display: flex;
              align-items: center;
              margin-bottom: 12px;
            `;

            titleRow.appendChild(title);
            titleRow.appendChild(importTypeLabel);

            // 描述
            const desc = document.createElement("div");
            desc.className = "code-package-description";
            desc.style.cssText = `
              color: #aaa;
              margin: 10px 0 20px;
              font-size: 13px;
              flex-grow: 1;
              line-height: 1.5;
              white-space:pre-line;
            `;

            // 使用Markdown解析描述内容
            try {
              if (window.marked) {
                desc.innerHTML = marked.parse(pkg.description);

                // 为描述中的链接添加样式和目标
                const links = desc.querySelectorAll("a");
                links.forEach((link) => {
                  link.style.cssText = `
                    color: #4d8af0;
                    text-decoration: none;
                    border-bottom: 1px dotted #4d8af0;
                  `;
                  link.setAttribute("target", "_blank");
                  link.setAttribute("rel", "noopener noreferrer");
                });
              } else {
                // 如果marked库未加载，回退到普通文本显示
                desc.style.whiteSpace = "pre-line";
                desc.textContent = pkg.description;
              }
            } catch (e) {
              // 解析出错时回退到普通文本
              desc.style.whiteSpace = "pre-line";
              desc.textContent = pkg.description;
              console.error("Markdown解析错误:", e);
            }

            // 卡片底部
            const cardFooter = document.createElement("div");
            cardFooter.style.cssText = `
              display: flex;
              justify-content: space-between;
              align-items: center;
              font-size: 12px;
              color: #888;
            `;

            // 添加发布时间
            const timestamp = document.createElement("div");
            timestamp.style.cssText = `
              display: flex;
              align-items: center;
              font-size: 12px;
              color: #888;
            `;

            // 时间图标
            const timeIcon = document.createElement("div");
            timeIcon.style.cssText = `
              width: 14px;
              height: 14px;
              margin-right: 6px;
              background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpolyline points='12 6 12 12 16 14'%3E%3C/polyline%3E%3C/svg%3E");
                background-repeat: no-repeat;
                background-size: contain;
            `;
            timestamp.appendChild(timeIcon);

            // 格式化时间戳
            let publishDate = "未知时间";
            if (pkg.time) {
              const date = new Date(pkg.time * 1000);
              publishDate = `${date.getFullYear()}-${String(
                date.getMonth() + 1
              ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
            }

            const timeText = document.createElement("span");
            timeText.textContent = publishDate;
            timestamp.appendChild(timeText);

            // 添加时间显示到底部
            cardFooter.appendChild(timestamp);

            if (/^https?:\/\//.test(pkg.docUrl)) {
              // 帮助按钮
              const helpBtn = document.createElement("button");
              helpBtn.textContent = "查看文档";
              helpBtn.style.cssText = `
                background-color: rgba(77, 138, 240, 0.2);
                color: #4d8af0;
                border: 1px solid rgba(77, 138, 240, 0.3);
                border-radius: 6px;
                padding: 8px 14px;
                font-size: 13px;
                cursor: pointer;
                transition: all 0.2s ease;
                margin-left: auto;
              `;

              helpBtn.addEventListener("mouseover", () => {
                helpBtn.style.backgroundColor = "rgba(77, 138, 240, 0.3)";
                helpBtn.style.transform = "translateY(-2px)";
              });

              helpBtn.addEventListener("mouseout", () => {
                helpBtn.style.backgroundColor = "rgba(77, 138, 240, 0.2)";
                helpBtn.style.transform = "translateY(0)";
              });

              // 更新帮助按钮点击事件，打开文档URL
              helpBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                window.open(pkg.docUrl, "_blank");
              });
              cardFooter.appendChild(helpBtn);
            }

            // 导入按钮
            const importBtn = document.createElement("button");
            importBtn.textContent = "导入";
            importBtn.className = "import-btn";
            importBtn.style.cssText = `
              background-color: rgba(99, 230, 190, 0.2);
              color: #63e6be;
              border: 1px solid rgba(99, 230, 190, 0.3);
              border-radius: 6px;
              padding: 8px 14px;
              font-size: 13px;
              cursor: pointer;
              transition: all 0.2s ease;
              position: relative;
              margin-left: 10px;
            `;

            importBtn.addEventListener("mouseover", () => {
              importBtn.style.backgroundColor = "rgba(99, 230, 190, 0.3)";
              importBtn.style.transform = "translateY(-2px)";
            });

            importBtn.addEventListener("mouseout", () => {
              importBtn.style.backgroundColor = "rgba(99, 230, 190, 0.2)";
              importBtn.style.transform = "translateY(0)";
            });

            // 添加导入按钮点击事件
            importBtn.addEventListener("click", (e) => {
              e.stopPropagation();
              try {
                // 使用pkgData的副本而不是引用
                const packageData = { ...pkg };
                showImportConfirmation(packageData, card);
              } catch (err) {
                console.error("导入按钮点击错误:", err);
                showNotification(
                  "导入操作失败: " + (err.message || "未知错误"),
                  "error"
                );
              }
            });

            cardFooter.appendChild(importBtn);

            // 将所有元素添加到卡片
            cardContent.appendChild(titleRow);
            cardContent.appendChild(desc);
            cardContent.appendChild(cardFooter);
            card.appendChild(cardContent);

            // 将卡片添加到列表
            packageList.appendChild(card);
          });

          showNotification("代码包列表已更新", "success");
        })
        .catch((error) => {
          console.error("刷新代码包列表失败:", error);
          showNotification("刷新代码包列表失败: " + error.message, "error");

          // 显示错误信息
          packageList.innerHTML = `
            <div style="grid-column: 1 / -1; text-align: center; padding: 30px; color: #ff5555;">
              <div style="margin-bottom: 10px;">
                <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#ff5555" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
                  <line x1="12" y1="9" x2="12" y2="13"></line>
                  <line x1="12" y1="17" x2="12.01" y2="17"></line>
                </svg>
              </div>
              <div style="font-weight: 500; margin-bottom: 8px;">获取代码包失败</div>
              <div style="font-size: 13px;">${
                error.message || "请稍后再试"
              }</div>
            </div>
          `;
        });
    }
  }
}
